<template>
  <div class="trading-container">
    <el-row :gutter="20">
      <!-- 市场概览 -->
      <el-col :span="24">
        <MarketOverview 
          :data-sources="dataSources"
          :selected-data-source="selectedDataSource"
          :is-loading="isLoading"
          :last-updated="lastUpdated"
          :market-overview="marketOverview"
          @fetch-data-by-source="fetchDataBySource"
          @toggle-auto-refresh="toggleAutoRefresh"
          @update:selected-data-source="val => selectedDataSource = val"
          @update:auto-refresh="val => autoRefresh = val"
        />
      </el-col>
    </el-row>

    <!-- 多数据源比较 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <DataSourceComparison 
          :is-loading="isLoading"
          :comparison-data="comparisonData"
          @fetch-all-data-sources="fetchAllDataSources"
        />
      </el-col>
    </el-row>

    <!-- Binance 交易图表 - 单独占一行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <BinanceChart 
          :binance-current-price="binanceCurrentPrice"
          :binance-symbol="binanceSymbol"
          :symbols="symbols"
          @update-binance-chart="updateBinanceChart"
          @update:binance-symbol="val => binanceSymbol = val"
        />
      </el-col>
    </el-row>

    <!-- 交易回测功能 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>交易策略回测</span>
              <div>
                <el-button type="warning" size="small" @click="startVirtualTrading" :loading="isVirtualTrading && !virtualTradingInterval">
                  {{ isVirtualTrading ? '停止虚拟交易' : '虚拟交易' }}
                </el-button>
                <el-button type="primary" size="small" @click="runBacktest" :loading="isBacktesting">运行回测</el-button>
                <el-button type="success" size="small" @click="saveStrategy" :disabled="!backtestResults.equityCurve || !backtestResults.equityCurve.length">保存策略</el-button>
                <el-button size="small" @click="loadStrategy">加载策略</el-button>
              </div>
            </div>
          </template>
          
          <BacktestSettings 
            v-model:backtest-settings="backtestSettings"
            :symbols="symbols"
            :is-backtesting="isBacktesting"
            :is-virtual-trading="isVirtualTrading"
            :virtual-trading-interval="virtualTradingInterval"
            :backtest-results="backtestResults"
            @run-backtest="runBacktest"
            @start-virtual-trading="startVirtualTrading"
            @save-strategy="saveStrategy"
            @load-strategy="loadStrategy"
          />
            
            <!-- 策略参数 -->
            <StrategyParameters :backtest-settings="backtestSettings" />
            
            <!-- 风险管理 -->
            <RiskManagement :backtest-settings="backtestSettings" />
            
          <!-- 回测结果详细信息 -->
          <BacktestDetails 
            :backtest-results="backtestResults"
            :backtest-summary="backtestSummary"
            :backtest-trades="backtestTrades"
          />
            
          <!-- 虚拟交易控制面板 -->
          <VirtualTradingControls 
            :is-virtual-trading="isVirtualTrading"
            :backtest-settings="backtestSettings"
            :virtual-trading-results="virtualTradingResults"
            :binance-symbol="binanceSymbol"
            :binance-current-price="binanceCurrentPrice"
            @stop-virtual-trading="stopVirtualTrading"
            @export-virtual-trading-data="exportVirtualTradingData"
            @manual-save-state="manualSaveState"
            @clear-virtual-trading-state="clearVirtualTradingState"
          />
          
          <!-- 数据源说明卡片 -->
          <el-card v-if="backtestSettings.dataSource === 'real'" shadow="hover" style="margin-top: 20px; background: #f0f9ff; border: 1px solid #7dd3fc;">
            <template #header>
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-icon color="#0284c7"><Connection /></el-icon>
                <span style="color: #0284c7; font-weight: bold;">真实数据源说明</span>
              </div>
            </template>
            <div style="color: #0c4a6e; line-height: 1.6;">
              <p style="margin: 0 0 10px 0;"><strong>数据获取顺序：</strong></p>
              <ol style="margin: 0; padding-left: 20px;">
                <li><strong>Binance API</strong> - 优先使用，数据质量最高，实时更新</li>
                <li><strong>CryptoCompare API</strong> - 备用数据源，提供丰富的历史数据</li>
                <li><strong>CoinGecko API</strong> - 第三备用数据源，免费使用</li>
              </ol>
              <p style="margin: 10px 0 0 0; font-size: 14px; color: #64748b;">
                ℹ️ 系统将自动尝试多个数据源，确保获取最优质的历史数据进行回测。
              </p>
            </div>
          </el-card>
          
          <!-- 虚拟交易状态面板 -->
          <el-card v-if="isVirtualTrading" shadow="hover" style="margin-top: 20px; background: #fff7ed; border: 1px solid #fb923c;">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; flex-direction: column; gap: 8px;">
                  <!-- 主标题行 -->
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <el-icon color="#ea580c" size="20"><TrendCharts /></el-icon>
                    <span style="color: #ea580c; font-weight: bold; font-size: 16px;">虚拟交易运行中</span>
                    <el-tag type="success" size="default" style="margin-left: 8px; font-weight: bold;">
                      {{ backtestSettings.symbol }}
                    </el-tag>
                  </div>
                  <!-- 策略信息行 -->
                  <div style="display: flex; align-items: center; gap: 8px; margin-left: 28px;">
                    <el-tag type="warning" size="small">
                      策略: {{ 
                        backtestSettings.strategyType === 'ma_cross' ? 'MA交叉' :
                        backtestSettings.strategyType === 'rsi' ? 'RSI策略' :
                        backtestSettings.strategyType === 'bollinger' ? '布林带' : '自定义'
                      }}
                    </el-tag>
                    <el-tag type="info" size="small">
                      初始资金: ${{ backtestSettings.initialCapital.toLocaleString() }}
                    </el-tag>
                    <el-tag type="primary" size="small">
                      数据源: 市场概览
                    </el-tag>
                    <el-tag 
                      :type="virtualTradingResults.pnl >= 0 ? 'success' : 'danger'" 
                      size="small"
                      style="font-weight: bold;"
                    >
                      {{ virtualTradingResults.pnl >= 0 ? '+' : '' }}{{ virtualTradingResults.pnlPercent.toFixed(2) }}%
                    </el-tag>
                  </div>
                </div>
                <div style="display: flex; gap: 8px;">
                  <el-button type="info" size="small" @click="exportVirtualTradingData" :disabled="!virtualTradingResults.trades.length" title="导出交易数据">
                    <el-icon><Download /></el-icon> 导出数据
                  </el-button>
                  <el-button type="success" size="small" @click="manualSaveState" title="手动保存状态">
                    <el-icon><Download /></el-icon> 保存状态
                  </el-button>
                  <el-button type="warning" size="small" @click="clearVirtualTradingState" title="清理保存的状态">
                    <el-icon><Delete /></el-icon> 清理状态
                  </el-button>
                  <el-button type="danger" size="small" @click="stopVirtualTrading">
                    <el-icon><VideoPause /></el-icon> 停止交易
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">交易对</div>
                  <div class="stat-value" style="font-weight: bold; color: #ea580c; font-size: 16px;">{{ backtestSettings.symbol }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">当前价格</div>
                  <div class="stat-value">${{ virtualTradingResults.currentPrice.toFixed(2) }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">现金余额</div>
                  <div class="stat-value">${{ virtualTradingResults.cash.toFixed(2) }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">持仓数量</div>
                  <div class="stat-value">{{ virtualTradingResults.position.toFixed(4) }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">持仓价值</div>
                  <div class="stat-value">${{ (virtualTradingResults.position * virtualTradingResults.currentPrice).toFixed(2) }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">总资产</div>
                  <div class="stat-value" style="font-weight: bold; color: #1890ff; font-size: 16px;">${{ virtualTradingResults.totalValue.toFixed(2) }}</div>
                </div>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 15px;">
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">策略类型</div>
                  <div class="stat-value" style="font-weight: bold; color: #722ed1;">{{ 
                    backtestSettings.strategyType === 'ma_cross' ? 'MA交叉' :
                    backtestSettings.strategyType === 'rsi' ? 'RSI策略' :
                    backtestSettings.strategyType === 'bollinger' ? '布林带' : '自定义'
                  }}</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">策略参数</div>
                  <div class="stat-value" style="font-size: 12px; font-weight: bold;">
                    <span v-if="backtestSettings.strategyType === 'ma_cross'" style="color: #1890ff;">
                      快{{ backtestSettings.fastMAPeriod }} / 慢{{ backtestSettings.slowMAPeriod }}
                    </span>
                    <span v-else-if="backtestSettings.strategyType === 'rsi'" style="color: #52c41a;">
                      RSI{{ backtestSettings.rsiPeriod }} ({{ backtestSettings.oversold }}-{{ backtestSettings.overbought }})
                    </span>
                    <span v-else-if="backtestSettings.strategyType === 'bollinger'" style="color: #fa8c16;">
                      BB{{ backtestSettings.bbPeriod }}, ±{{ backtestSettings.bbStdDev }}σ
                    </span>
                    <span v-else style="color: #722ed1;">自定义策略</span>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">盈亏金额</div>
                  <div class="stat-value" :class="virtualTradingResults.pnl >= 0 ? 'profit' : 'loss'">
                    {{ virtualTradingResults.pnl >= 0 ? '+' : '' }}${{ virtualTradingResults.pnl.toFixed(2) }}
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">盈亏率</div>
                  <div class="stat-value" :class="virtualTradingResults.pnlPercent >= 0 ? 'profit' : 'loss'">
                    {{ virtualTradingResults.pnlPercent >= 0 ? '+' : '' }}{{ virtualTradingResults.pnlPercent.toFixed(2) }}%
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">交易次数</div>
                  <div class="stat-value">{{ virtualTradingResults.currentSessionTradesCount }}</div>
                  <div class="stat-detail" style="font-size: 10px; color: #666;">
                    当前会话: {{ virtualTradingResults.currentSessionTradesCount }} | 历史总计: {{ virtualTradingResults.trades.length }}
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="virtual-stat-item">
                  <div class="stat-label">风险控制</div>
                  <div class="stat-value" style="font-size: 12px; font-weight: bold;">
                    <span style="color: #f5222d;">止损{{ backtestSettings.stopLoss }}%</span> / 
                    <span style="color: #52c41a;">止盈{{ backtestSettings.takeProfit }}%</span>
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <!-- 实时状态信息行 -->
            <el-row :gutter="20" style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 6px;">
              <el-col :span="6">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#52c41a" size="16"><Clock /></el-icon>
                  <span style="font-size: 12px; color: #666;">运行状态:</span>
                  <el-tag type="success" size="small">正在运行</el-tag>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#1890ff" size="16"><Connection /></el-icon>
                  <span style="font-size: 12px; color: #666;">数据来源:</span>
                  <el-tag 
                    :type="binanceSymbol === backtestSettings.symbol.replace('/', '') && binanceCurrentPrice > 0 ? 'success' : 'info'" 
                    size="small"
                  >
                    {{ binanceSymbol === backtestSettings.symbol.replace('/', '') && binanceCurrentPrice > 0 ? 'Binance实时' : '市场数据' }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#fa8c16" size="16"><Warning /></el-icon>
                  <span style="font-size: 12px; color: #666;">风险状态:</span>
                  <el-tag :type="backtestSettings.riskControl ? 'success' : 'warning'" size="small">
                    {{ backtestSettings.riskControl ? '已开启' : '已关闭' }}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#722ed1" size="16"><DataAnalysis /></el-icon>
                  <span style="font-size: 12px; color: #666;">最大回撤:</span>
                  <el-tag :type="virtualTradingResults.currentDrawdown > backtestSettings.initialCapital * 0.1 ? 'danger' : 'info'" size="small">
                    ${{ virtualTradingResults.currentDrawdown?.toFixed(2) || '0.00' }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
            
            <!-- 最近交易记录 -->
            <div v-if="virtualTradingResults.trades.length > 0" style="margin-top: 20px;">
              <el-divider>最近交易记录</el-divider>
              <div style="max-height: 150px; overflow-y: auto;">
                <div 
                  v-for="trade in virtualTradingResults.trades.slice(-5).reverse()" 
                  :key="trade.id"
                  class="trade-record"
                  :class="trade.type"
                >
                  <span class="trade-type">{{ trade.type === 'buy' ? '买入' : '卖出' }}</span>
                  <span class="trade-price">${{ trade.price.toFixed(2) }}</span>
                  <span class="trade-amount">{{ trade.amount.toFixed(4) }}</span>
                  <span class="trade-reason">{{ trade.reason }}</span>
                  <span class="trade-time">{{ trade.time }}</span>
                  <span v-if="trade.profit !== undefined" class="trade-profit" :class="trade.profit >= 0 ? 'profit' : 'loss'">
                    {{ trade.profit >= 0 ? '+' : '' }}${{ trade.profit.toFixed(2) }}
                  </span>
                </div>
              </div>
            </div>
          </el-card>
          
          <!-- 交易统计面板 -->
          <el-card v-if="isVirtualTrading && virtualTradingResults.trades.length > 0" shadow="hover" style="margin-top: 20px; background: #f8fafc; border: 1px solid #e2e8f0;">
            <template #header>
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-icon color="#3b82f6"><DataAnalysis /></el-icon>
                <span style="color: #3b82f6; font-weight: bold;">交易统计分析</span>
              </div>
            </template>
            
            <el-row :gutter="15">
              <!-- 基本统计 -->
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">交易次数</div>
                  <div class="stat-number">{{ virtualTradingStatistics.totalTrades }}</div>
                  <div class="stat-detail">
                    盈利: {{ virtualTradingStatistics.winningTrades }} | 亏损: {{ virtualTradingStatistics.losingTrades }}
                  </div>
                </div>
              </el-col>
              
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">胜率</div>
                  <div class="stat-number" :class="virtualTradingStatistics.winRate >= 50 ? 'profit' : 'loss'">
                    {{ virtualTradingStatistics.winRate }}%
                  </div>
                  <div class="stat-detail">
                    盈亏比: {{ virtualTradingStatistics.profitFactor || 'N/A' }}
                  </div>
                </div>
              </el-col>
              
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">平均盈亏</div>
                  <div class="stat-number">
                    <span class="profit">+${{ virtualTradingStatistics.averageWin }}</span> / 
                    <span class="loss">-${{ virtualTradingStatistics.averageLoss }}</span>
                  </div>
                  <div class="stat-detail">
                    最大: <span class="profit">+${{ virtualTradingStatistics.maxWin }}</span> / 
                    <span class="loss">${{ virtualTradingStatistics.maxLoss }}</span>
                  </div>
                </div>
              </el-col>
              
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">最大回撤</div>
                  <div class="stat-number loss">
                    ${{ virtualTradingStatistics.maxDrawdown }}
                  </div>
                  <div class="stat-detail">
                    {{ virtualTradingStatistics.maxDrawdownPercent }}%
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <el-row :gutter="15" style="margin-top: 15px;">
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-title">总收益率</div>
                  <div class="stat-number" :class="virtualTradingStatistics.totalReturn >= 0 ? 'profit' : 'loss'">
                    {{ virtualTradingStatistics.totalReturn >= 0 ? '+' : '' }}{{ virtualTradingStatistics.totalReturn }}%
                  </div>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-title">夏普比率</div>
                  <div class="stat-number" :class="virtualTradingStatistics.sharpeRatio > 1 ? 'profit' : virtualTradingStatistics.sharpeRatio > 0 ? 'neutral' : 'loss'">
                    {{ virtualTradingStatistics.sharpeRatio }}
                  </div>
                  <div class="stat-detail">
                    风险调整后收益
                  </div>
                </div>
              </el-col>
              
              <el-col :span="8">
                <div class="stat-card">
                  <div class="stat-title">交易天数</div>
                  <div class="stat-number">{{ virtualTradingStatistics.tradingDays }}</div>
                  <div class="stat-detail">
                    策略: {{ 
                      backtestSettings.strategyType === 'ma_cross' ? 'MA交叉' :
                      backtestSettings.strategyType === 'rsi' ? 'RSI策略' :
                      backtestSettings.strategyType === 'bollinger' ? '布林带' : '自定义'
                    }}
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>
          
          <!-- 回测结果 -->
          <div v-if="backtestResults.equityCurve && backtestResults.equityCurve.length" class="backtest-results">
            <el-divider></el-divider>
            <h3>回测结果摘要</h3>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">总收益率</div>
                    <div class="result-value" :class="{ 'up': backtestSummary.totalReturn > 0, 'down': backtestSummary.totalReturn < 0 }">
                      {{ backtestSummary.totalReturn > 0 ? '+' : '' }}{{ backtestSummary.totalReturn.toFixed(2) }}%
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">年化收益率</div>
                    <div class="result-value" :class="{ 'up': backtestSummary.annualReturn > 0, 'down': backtestSummary.annualReturn < 0 }">
                      {{ backtestSummary.annualReturn > 0 ? '+' : '' }}{{ backtestSummary.annualReturn.toFixed(2) }}%
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">夏普比率</div>
                    <div class="result-value">{{ backtestSummary.sharpeRatio.toFixed(2) }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">最大回撤</div>
                    <div class="result-value">{{ backtestSummary.maxDrawdown.toFixed(2) }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">胜率</div>
                    <div class="result-value">{{ backtestSummary.winRate.toFixed(2) }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="result-item">
                    <div class="result-label">总交易次数</div>
                    <div class="result-value">{{ backtestSummary.totalTrades }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 回测图表 -->
            <div class="backtest-chart-container" style="margin-top: 20px; height: 400px;">
              <div ref="backtestChart" style="width: 100%; height: 100%;"></div>
            </div>
            
            <!-- 交易记录 -->
            <el-divider></el-divider>
            <h3>交易记录</h3>
            <!-- 回测结果统计 -->
            <el-card shadow="hover" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>回测结果统计</span>
                </div>
              </template>
              <div class="result-stats">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">总收益率</div>
                      <div class="stat-value" :class="backtestSummary.totalReturn >= 0 ? 'profit' : 'loss'">
                        {{ backtestSummary.totalReturn.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">年化收益率</div>
                      <div class="stat-value" :class="backtestSummary.annualReturn >= 0 ? 'profit' : 'loss'">
                        {{ backtestSummary.annualReturn.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">夏普比率</div>
                      <div class="stat-value">
                        {{ backtestSummary.sharpeRatio.toFixed(2) }}
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">最大回撤</div>
                      <div class="stat-value loss">
                        {{ backtestSummary.maxDrawdown.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">胜率</div>
                      <div class="stat-value">
                        {{ backtestSummary.winRate.toFixed(2) }}%
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-label">总交易次数</div>
                      <div class="stat-value">
                        {{ backtestSummary.totalTrades }}
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <!-- 交易记录表格 -->
            <el-card shadow="hover" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>交易记录</span>
                </div>
              </template>
              <el-table :data="backtestTrades" style="width: 100%;" stripe>
                <el-table-column prop="date" label="日期" width="120" sortable />
                <el-table-column prop="type" label="类型" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'" size="small">
                      {{ scope.row.type === 'buy' ? '买入' : '卖出' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="120">
                  <template #default="scope">
                    ${{ scope.row.price.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="数量" width="120" />
                <el-table-column prop="value" label="价值" width="120">
                  <template #default="scope">
                    ${{ scope.row.value.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="profit" label="盈亏" width="120" v-if="backtestTrades.some(t => t.profit !== undefined)">
                  <template #default="scope">
                    <span v-if="scope.row.profit !== undefined" 
                          :class="scope.row.profit >= 0 ? 'profit' : 'loss'">
                      ${{ scope.row.profit.toFixed(2) }}
                    </span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElLoading, ElMessageBox, ElNotification } from 'element-plus'
import { 
  TrendCharts, 
  DataAnalysis, 
  Download, 
  Delete, 
  VideoPause, 
  Connection,
  Clock,
  Warning,
  CaretTop,
  CaretBottom,
  QuestionFilled
} from '@element-plus/icons-vue'
import axios from 'axios'
import { 
  calculateMA, 
  calculateRSI, 
  calculateBollingerBands, 
  runMACrossStrategy, 
  runRSIStrategy, 
  runBollingerStrategy, 
  runCustomStrategy, 
  runVWAPStrategy, 
  runMLStrategy1,
  fetchHistoricalData,
  fetchRealHistoricalData,
  generateMockHistoricalData
} from './additionalStrategies.js'

// 导入VWAP策略相关函数
import {
  calculateVWAP,
  generateRealTimeVWAPSignal,
  generateVWAPSignal
} from './vwapStrategies.js'

// 导入ML策略相关函数
import {
  calculateMLFeatures,
  calculateSMA,
  calculateMACD,
  calculateEMA,
  calculateBB,
  calculateATR,
  calculateVolatility,
  calculateSupportResistance,
  calculateTrendSlope,
  identifyMarketState,
  performMLPrediction,
  calculateTrendScore,
  calculateMomentumScore,
  calculateReversalScore,
  calculateVolumeScore,
  calculateVolatilityScore,
  getMarketStateMultiplier,
  calculateAdvancedSentimentIndicator,
  calculateFearIndex,
  calculateGreedIndex,
  calculateTechnicalExtreme,
  getFeatureWeights,
  evaluateRiskConditions,
  calculateDynamicPosition,
  calculateAdaptiveStopLoss,
  calculateAdaptiveTakeProfit,
  checkMLStopConditions,
  calculateStrategyPerformance,
  calculateAvgHoldingPeriod,
  calculateMaxConsecutive,
  calculateMaxDrawdownFromCurve,
  calculateEquityVolatility,
  calculateRiskAdjustedReturn,
  generateStrategyRecommendation
} from './mlStrategies.js'

// 导入拆分的子组件
import MarketOverview from './components/MarketOverview.vue'
import DataSourceComparison from './components/DataSourceComparison.vue'
import BinanceChart from './components/BinanceChart.vue'
import BacktestSettings from './components/BacktestSettings.vue'
import StrategyParameters from './components/StrategyParameters.vue'
import RiskManagement from './components/RiskManagement.vue'
import VirtualTradingPanel from './components/VirtualTradingPanel.vue'
import TradingStatistics from './components/TradingStatistics.vue'
import BacktestResults from './components/BacktestResults.vue'
// 新增的拆分组件
import BacktestSummary from './components/BacktestSummary.vue'
import BacktestStats from './components/BacktestStats.vue'
import TradeRecords from './components/TradeRecords.vue'
import BacktestChart from './components/BacktestChart.vue'
// 进一步拆分的组件
import VirtualTradingControls from './components/VirtualTradingControls.vue'
import TradingStatsDisplay from './components/TradingStatsDisplay.vue'
import BacktestDetails from './components/BacktestDetails.vue'

export default {
  name: 'Trading',
  components: {
    TrendCharts,
    DataAnalysis,
    Download,
    Delete,
    VideoPause,
    Connection,
    Clock,
    Warning,
    CaretTop,
    CaretBottom,
    QuestionFilled,
    // 注册拆分的子组件
    MarketOverview,
    DataSourceComparison,
    BinanceChart,
    BacktestSettings,
    StrategyParameters,
    RiskManagement,
    VirtualTradingPanel,
    TradingStatistics,
    BacktestResults,
    // 新增的拆分组件
    BacktestSummary,
    BacktestStats,
    TradeRecords,
    BacktestChart,
    // 进一步拆分的组件
    VirtualTradingControls,
    TradingStatsDisplay,
    BacktestDetails
  },
  setup() {
    // 数据源选择
    const dataSources = [
      { value: 'coingecko', label: 'CoinGecko' },
      { value: 'binance', label: 'Binance' },
      { value: 'cryptocompare', label: 'CryptoCompare' }
    ]
    const selectedDataSource = ref('coingecko')
    const isLoading = ref(false)
    const lastUpdated = ref(new Date().toLocaleString())
    const autoRefresh = ref(true)
    const refreshInterval = ref(null)
    
    // 多数据源比较数据
    const comparisonData = reactive([
      { 
        symbol: 'BTC/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'ETH/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'BNB/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'SOL/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      }
    ])
    
    // 计算价格差异
    const calculatePriceDiff = (symbol) => {
      const item = comparisonData.find(item => item.symbol === symbol)
      if (!item) return
      
      const prices = [
        parseFloat(item.coingecko.price.replace(/,/g, '')) || 0,
        parseFloat(item.binance.price.replace(/,/g, '')) || 0,
        parseFloat(item.cryptocompare.price.replace(/,/g, '')) || 0
      ].filter(price => price > 0)
      
      if (prices.length < 2) {
        item.priceDiff = 0
        return
      }
      
      const maxPrice = Math.max(...prices)
      const minPrice = Math.min(...prices)
      item.priceDiff = ((maxPrice - minPrice) / minPrice) * 100
    }
    
    // 获取所有数据源的数据
    const fetchAllDataSources = async () => {
      try {
        isLoading.value = true
        // 并行获取所有三个数据源的数据
        await Promise.all([
          fetchCoinGeckoData(false),
          fetchBinanceData(false),
          fetchCryptoCompareData(false)
        ])
        
        // 计算所有交易对的价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        lastUpdated.value = new Date().toLocaleString()
        ElMessage({
          message: '所有数据源更新成功',
          type: 'success'
        })
      } catch (error) {
        console.error('更新数据源失败:', error)
        ElMessage({
          message: '部分数据源更新失败，请稍后重试',
          type: 'warning'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 启动自动刷新
    const startAutoRefresh = () => {
      if (refreshInterval.value) clearInterval(refreshInterval.value)
      refreshInterval.value = setInterval(() => {
        fetchAllDataSources() // 每分钟刷新所有三个数据源的数据
      }, 60000) // 60秒
    }
    
    // 停止自动刷新
    const stopAutoRefresh = () => {
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
        refreshInterval.value = null
      }
    }
    
    // 切换自动刷新状态
    const toggleAutoRefresh = () => {
      if (autoRefresh.value) {
        startAutoRefresh()
      } else {
        stopAutoRefresh()
      }
    }
    
    // 市场概览数据
    const marketOverview = reactive([
      { name: 'BTC/USDT', price: '加载中...', change: 0 },
      { name: 'ETH/USDT', price: '加载中...', change: 0 },
      { name: 'BNB/USDT', price: '加载中...', change: 0 },
      { name: 'SOL/USDT', price: '加载中...', change: 0 }
    ])
    
    // 获取CoinGecko数据
    const fetchCoinGeckoData = async (showMessage = true) => {
      try {
        isLoading.value = true
        const response = await axios.get('https://api.coingecko.com/api/v3/simple/price', {
          params: {
            ids: 'bitcoin,ethereum,binancecoin,solana',
            vs_currencies: 'usd',
            include_24hr_change: 'true'
          }
        })
        
        const data = response.data
        
        // 更新市场概览数据
        marketOverview[0].price = data.bitcoin.usd.toLocaleString()
        marketOverview[0].change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        marketOverview[1].price = data.ethereum.usd.toLocaleString()
        marketOverview[1].change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        marketOverview[2].price = data.binancecoin.usd.toLocaleString()
        marketOverview[2].change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        marketOverview[3].price = data.solana.usd.toLocaleString()
        marketOverview[3].change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].coingecko.price = data.bitcoin.usd.toLocaleString()
        comparisonData[0].coingecko.change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        comparisonData[1].coingecko.price = data.ethereum.usd.toLocaleString()
        comparisonData[1].coingecko.change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        comparisonData[2].coingecko.price = data.binancecoin.usd.toLocaleString()
        comparisonData[2].coingecko.change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        comparisonData[3].coingecko.price = data.solana.usd.toLocaleString()
        comparisonData[3].coingecko.change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 更新K线图表数据，仅当当前选中的数据源是CoinGecko时
        if (selectedDataSource.value === 'coingecko') {
          updateChartData(data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CoinGecko数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CoinGecko数据失败:', error)
        ElMessage({
          message: '获取CoinGecko数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取Binance数据
    const fetchBinanceData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 并行请求多个交易对数据
        const [btcResponse, ethResponse, bnbResponse, solResponse] = await Promise.all([
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=ETHUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BNBUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=SOLUSDT')
        ])
        
        // 更新市场概览数据
        marketOverview[0].price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        marketOverview[0].change = parseFloat(btcResponse.data.priceChangePercent)
        
        marketOverview[1].price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        marketOverview[1].change = parseFloat(ethResponse.data.priceChangePercent)
        
        marketOverview[2].price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        marketOverview[2].change = parseFloat(bnbResponse.data.priceChangePercent)
        
        marketOverview[3].price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        marketOverview[3].change = parseFloat(solResponse.data.priceChangePercent)
        
        // 更新比较数据
        comparisonData[0].binance.price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        comparisonData[0].binance.change = parseFloat(btcResponse.data.priceChangePercent)
        
        comparisonData[1].binance.price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        comparisonData[1].binance.change = parseFloat(ethResponse.data.priceChangePercent)
        
        comparisonData[2].binance.price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        comparisonData[2].binance.change = parseFloat(bnbResponse.data.priceChangePercent)
        
        comparisonData[3].binance.price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        comparisonData[3].binance.change = parseFloat(solResponse.data.priceChangePercent)
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取K线数据
        const klineResponse = await axios.get('https://api.binance.com/api/v3/klines', {
          params: {
            symbol: 'BTCUSDT',
            interval: '1d',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是Binance时
        if (selectedDataSource.value === 'binance') {
          updateChartWithBinanceData(klineResponse.data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'Binance数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取Binance数据失败:', error)
        ElMessage({
          message: '获取Binance数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取CryptoCompare数据
    const fetchCryptoCompareData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 获取多个币种的价格数据
        const priceResponse = await axios.get('https://min-api.cryptocompare.com/data/pricemultifull', {
          params: {
            fsyms: 'BTC,ETH,BNB,SOL',
            tsyms: 'USD'
          }
        })
        
        const data = priceResponse.data.RAW
        
        // 更新市场概览数据
        marketOverview[0].price = data.BTC.USD.PRICE.toLocaleString()
        marketOverview[0].change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[1].price = data.ETH.USD.PRICE.toLocaleString()
        marketOverview[1].change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[2].price = data.BNB.USD.PRICE.toLocaleString()
        marketOverview[2].change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[3].price = data.SOL.USD.PRICE.toLocaleString()
        marketOverview[3].change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].cryptocompare.price = data.BTC.USD.PRICE.toLocaleString()
        comparisonData[0].cryptocompare.change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[1].cryptocompare.price = data.ETH.USD.PRICE.toLocaleString()
        comparisonData[1].cryptocompare.change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[2].cryptocompare.price = data.BNB.USD.PRICE.toLocaleString()
        comparisonData[2].cryptocompare.change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[3].cryptocompare.price = data.SOL.USD.PRICE.toLocaleString()
        comparisonData[3].cryptocompare.change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取历史K线数据
        const historyResponse = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
          params: {
            fsym: 'BTC',
            tsym: 'USD',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是CryptoCompare时
        if (selectedDataSource.value === 'cryptocompare') {
          updateChartWithCryptoCompareData(historyResponse.data.Data.Data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CryptoCompare数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CryptoCompare数据失败:', error)
        ElMessage({
          message: '获取CryptoCompare数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 根据选择的数据源获取数据
    const fetchDataBySource = () => {
      switch (selectedDataSource.value) {
        case 'coingecko':
          fetchCoinGeckoData()
          break
        case 'binance':
          fetchBinanceData()
          break
        case 'cryptocompare':
          fetchCryptoCompareData()
          break
      }
    }

    // 交易对选择
    const symbols = [
      { value: 'BTC/USDT', label: 'BTC/USDT' },
      { value: 'ETH/USDT', label: 'ETH/USDT' },
      { value: 'BNB/USDT', label: 'BNB/USDT' },
      { value: 'SOL/USDT', label: 'SOL/USDT' }
    ]
    const selectedSymbol = ref('BTC/USDT')
    
    // Binance 图表相关
    const binanceSymbol = ref('BTCUSDT')
    const binanceWebview = ref(null)
    const binanceCurrentPrice = ref(0) // 新增：当前Binance图表对应的实时价格
    const binancePriceUpdateInterval = ref(null) // 新增：价格更新定时器
    
    // 更新 Binance 图表
    const updateBinanceChart = (newSymbol) => {
      binanceSymbol.value = newSymbol
      if (binanceWebview.value) {
        binanceWebview.value.src = `https://www.binance.com/zh-CN/trade/${newSymbol}?theme=dark&type=spot`
      }
      
      // 启动对应交易对的实时价格监控
      startBinancePriceMonitoring(newSymbol)
    }
    
    // 启动Binance价格实时监控
    const startBinancePriceMonitoring = (symbol) => {
      // 清除现有定时器
      if (binancePriceUpdateInterval.value) {
        clearInterval(binancePriceUpdateInterval.value)
      }
      
      // 立即获取一次价格
      fetchBinanceRealTimePrice(symbol)
      
      // 每5秒获取一次实时价格，与Binance图表刷新频率保持同步
      binancePriceUpdateInterval.value = setInterval(() => {
        fetchBinanceRealTimePrice(symbol)
      }, 5000) // 5秒间隔，确保与图表更新同步
      
      console.log(`🔄 开始监控 ${symbol} 的实时价格`)
    }
    
    // 获取Binance实时价格
    const fetchBinanceRealTimePrice = async (symbol) => {
      try {
        const response = await axios.get('https://api.binance.com/api/v3/ticker/price', {
          params: { symbol },
          timeout: 3000
        })
        
        if (response.data && response.data.price) {
          const newPrice = parseFloat(response.data.price)
          const oldPrice = binanceCurrentPrice.value
          binanceCurrentPrice.value = newPrice
          
          // 同步更新市场概览中对应的价格
          updateMarketOverviewPrice(symbol, newPrice)
          
          // 如果虚拟交易正在运行且交易对匹配，同步更新虚拟交易价格
          updateVirtualTradingPrice(symbol, newPrice)
          
          // 价格变化提示（仅在价格有显著变化时显示）
          if (oldPrice > 0 && Math.abs((newPrice - oldPrice) / oldPrice) > 0.001) { // 0.1%以上变化
            console.log(`💰 ${symbol} 价格更新: $${oldPrice.toFixed(2)} → $${newPrice.toFixed(2)}`)
          }
        }
      } catch (error) {
        console.warn(`获取 ${symbol} 实时价格失败:`, error.message)
      }
    }
    
    // 同步更新市场概览价格
    const updateMarketOverviewPrice = (binanceSymbol, price) => {
      const symbolMap = {
        'BTCUSDT': 0,
        'ETHUSDT': 1,
        'BNBUSDT': 2,
        'SOLUSDT': 3
      }
      
      const index = symbolMap[binanceSymbol]
      if (index !== undefined && marketOverview[index]) {
        const oldPrice = parseFloat(marketOverview[index].price.replace(/,/g, '')) || 0
        marketOverview[index].price = price.toLocaleString()
        
        // 计算实时涨跌幅（基于之前的价格）
        if (oldPrice > 0) {
          const changePercent = ((price - oldPrice) / oldPrice) * 100
          if (Math.abs(changePercent) > 0.01) { // 0.01%以上变化才更新
            marketOverview[index].change = parseFloat(changePercent.toFixed(2))
          }
        }
        
        console.log(`📊 市场概览更新: ${marketOverview[index].name} = $${price.toLocaleString()}`)
      }
    }
    
    // 同步更新虚拟交易价格
    const updateVirtualTradingPrice = (binanceSymbol, price) => {
      if (!isVirtualTrading.value) return
      
      // 检查当前虚拟交易的交易对是否与Binance图表匹配
      const currentVirtualSymbol = backtestSettings.symbol.replace('/', '')
      if (currentVirtualSymbol === binanceSymbol) {
        // 更新虚拟交易的当前价格
        virtualTradingResults.currentPrice = price
        virtualTradingResults.lastUpdateTime = Date.now()
        
        // 添加到价格历史
        const now = Date.now()
        const priceData = {
          date: new Date(now).toISOString().split('T')[0],
          time: new Date(now).toLocaleTimeString(),
          close: price,
          timestamp: now
        }
        
        virtualTradingResults.priceHistory.push(priceData)
        
        // 保持最近100个价格数据点
        if (virtualTradingResults.priceHistory.length > 100) {
          virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
        }
        
        // 更新虚拟账户价值
        updateVirtualAccount()
        
        console.log(`🎯 虚拟交易价格同步: ${backtestSettings.symbol} = $${price.toFixed(2)}`)
      }
    }
    
    // 停止Binance价格监控
    const stopBinancePriceMonitoring = () => {
      if (binancePriceUpdateInterval.value) {
        clearInterval(binancePriceUpdateInterval.value)
        binancePriceUpdateInterval.value = null
        console.log('⏹️ 停止Binance价格监控')
      }
    }

    // 图表实例
    let chartInstance = null
    const tradingChart = ref(null)

    // 更新图表数据 - CoinGecko
    const updateChartData = (data) => {
      if (!chartInstance) return
      
      // 由于CoinGecko API不直接提供K线数据，我们使用模拟数据
      // 但使用实际价格作为基准
      const basePrice = data.bitcoin.usd
      const klineData = generateKLineData(basePrice)
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CoinGecko`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: klineData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: klineData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - Binance
    const updateChartWithBinanceData = (klineData) => {
      if (!chartInstance) return
      
      // Binance K线数据格式转换
      // [开盘时间, 开盘价, 最高价, 最低价, 收盘价, 成交量, 收盘时间, ...]
      const formattedData = klineData.map(item => {
        const date = new Date(item[0])
        return [
          date.toISOString().split('T')[0],
          parseFloat(item[1]), // 开盘价
          parseFloat(item[4]), // 收盘价
          parseFloat(item[3]), // 最低价
          parseFloat(item[2])  // 最高价
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: Binance`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - CryptoCompare
    const updateChartWithCryptoCompareData = (historyData) => {
      if (!chartInstance) return
      
      // CryptoCompare数据格式转换
      const formattedData = historyData.map(item => {
        const date = new Date(item.time * 1000)
        return [
          date.toISOString().split('T')[0],
          item.open,
          item.close,
          item.low,
          item.high
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CryptoCompare`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 初始化图表
    const initChart = () => {
      if (tradingChart.value) {
        chartInstance = echarts.init(tradingChart.value)
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          chartInstance.resize()
        })
        
        // 加载初始数据
        fetchDataBySource()
      }
    }
    
    // 生成模拟K线数据
    const generateKLineData = () => {
      const basePrice = 45000
      const data = []
      const today = new Date()
      
      for (let i = 0; i < 100; i++) {
        const date = new Date(today)
        date.setDate(date.getDate() - (100 - i))
        const dateStr = date.toISOString().split('T')[0]
        
        const open = basePrice + Math.random() * 2000 - 1000
        const close = open + Math.random() * 1000 - 500
        const low = Math.min(open, close) - Math.random() * 500
        const high = Math.max(open, close) + Math.random() * 500
        
        data.push([dateStr, open, close, low, high])
      }
      
      return data
    }
    
    onMounted(() => {
      // 初始化网络监控
      setupNetworkMonitoring()
      
      // 设置页面状态处理器
      const cleanupPageHandlers = setupPageStateHandlers()
      
      // 将清理函数保存到组件实例上，以便在unmounted时调用
      window._pageHandlersCleanup = cleanupPageHandlers
      
      // 首次加载时获取所有数据源的数据
      fetchAllDataSources()
      
      // 启动Binance图表对应交易对的实时价格监控
      startBinancePriceMonitoring(binanceSymbol.value)
      
      // 启动VWAP数据更新（如果选择了VWAP策略）
      if (backtestSettings.strategyType === 'vwap') {
        startVWAPDataUpdate()
      }
      
      // 检查是否有保存的虚拟交易状态
      setTimeout(() => {
        const savedState = loadVirtualTradingState()
        if (savedState && savedState.isActive) {
          ElMessageBox.confirm(
            `检测到上次未完成的虚拟交易：\n` +
            `交易对: ${savedState.symbol}\n` +
            `策略: ${savedState.strategy}\n` +
            `当前盈亏: ${savedState.pnlPercent.toFixed(2)}%\n` +
            `交易次数: ${savedState.trades.length}\n` +
            `最后更新: ${new Date(savedState.lastUpdated).toLocaleString()}\n\n` +
            `是否自动恢复上次的虚拟交易状态？`,
            '恢复虚拟交易',
            {
              confirmButtonText: '自动恢复',
              cancelButtonText: '稍后手动',
              type: 'question',
              center: true
            }
          ).then(() => {
            // 用户选择自动恢复
            restoreVirtualTradingState(savedState)
          }).catch(() => {
            // 用户选择稍后手动，不做任何操作
            console.log('用户选择稍后手动恢复虚拟交易')
          })
        }
      }, 2000) // 延迟2秒显示，等待页面加载完成
      
      // 启动自动刷新
      startAutoRefresh()
    })
    
    onUnmounted(() => {
      // 停止自动刷新
      stopAutoRefresh()
      
      // 停止Binance价格监控
      stopBinancePriceMonitoring()
      
      // 停止VWAP定时更新
      stopVWAPDataUpdate()
      
      // 清理虚拟交易定时器
      if (virtualTradingInterval.value) {
        clearInterval(virtualTradingInterval.value)
      }
      
      // 在组件销毁前保存状态
      if (isVirtualTrading.value) {
        console.log('💾 组件销毁，保存虚拟交易状态')
        saveVirtualTradingState()
      }
      
      // 清理页面状态处理器
      if (window._pageHandlersCleanup) {
        window._pageHandlersCleanup()
        window._pageHandlersCleanup = null
      }
    })
    
    // 回测相关变量
    const backtestSettings = reactive({
      symbol: 'BTC/USDT',
      period: '30d',
      interval: '1d',
      strategyType: 'ma_cross',
      dataSource: 'real', // 新增：数据源选择
      initialCapital: 10000,
      tradeAmount: 50,
      fastMAPeriod: 9,
      slowMAPeriod: 21,
      rsiPeriod: 14,
      overbought: 70,
      oversold: 30,
      bbPeriod: 20,
      bbStdDev: 2,
      customStrategy: '',
      stopLoss: 5,
      takeProfit: 10,
      maxPosition: 100, // 新增：最大仓位比例
      riskControl: true, // 新增：风险控制开关
      dynamicPositioning: false, // 新增：动态仓位管理
      maxDrawdownLimit: 15, // 新增：最大回撤限制
      // AI智能策略1参数
      mlConfidenceThreshold: 0.75, // 模型置信度阈值
      mlFeatureWeighting: 'balanced', // 特征权重模式
      mlMarketStateAware: true, // 市场状态感知
      mlDynamicPositioning: true, // 动态仓位管理
      mlSentimentWeight: 0.5, // 情绪指标权重
      mlAdaptiveStopLoss: 1.5, // 智能止损系数
      // 新增高级AI参数
      mlRiskFilter: true, // 风险过滤器
      mlSignalThreshold: 0.55, // 信号强度阈值
      mlMultiFactorMode: 'adaptive' // 多因子融合模式
    })
    
    const isBacktesting = ref(false)
    const backtestResults = ref({ equityCurve: [], trades: [] })
    const backtestTrades = ref([])
    const backtestSummary = reactive({
      totalReturn: 0,
      annualReturn: 0,
      sharpeRatio: 0,
      maxDrawdown: 0,
      winRate: 0,
      totalTrades: 0
    })
    const backtestChart = ref(null)
    const backtestChartInstance = ref(null)
    
    // 虚拟交易相关变量
    const isVirtualTrading = ref(false)
    const virtualTradingInterval = ref(null)
    // VWAP数据缓存
    const vwapDataCache = reactive({
      data: {}, // 按交易对存储的VWAP数据
      lastUpdate: {}, // 上次更新时间
      cacheExpiry: 5 * 60 * 1000 // 5分钟缓存过期时间
    })
    
    // VWAP定时器引用
    const vwapInterval = ref(null)
    const virtualTradingData = ref([])
    const virtualCurrentIndex = ref(0)
    const virtualTradingResults = reactive({
      cash: 0,
      position: 0,
      totalValue: 0,
      trades: [],
      currentPrice: 0,
      pnl: 0,
      pnlPercent: 0,
      priceHistory: [], // 新增：用于存储价格历史计算技术指标
      lastSignalTime: 0, // 新增：防止频繁交易
      lastUpdateTime: 0, // 新增：记录最后更新时间
      priceCache: null, // 新增：价格缓存
      cacheExpiry: 0, // 新增：缓存过期时间
      // 风险控制相关
      maxDrawdownReached: 0, // 最大回撤记录
      currentDrawdown: 0, // 当前回撤
      riskLocked: false, // 风险锁定状态
      lastStopLoss: null, // 最后一次止损价格
      lastTakeProfit: null, // 最后一次止盈价格
      positionValue: 0, // 当前仓位价值
      riskEvents: [], // 风险事件记录
      // 新增：当前会话交易跟踪
      currentSessionTradesCount: 0, // 当前会话的交易次数
      sessionStartTime: null // 会话开始时间
    })
    
    // 监听策略类型变化，动态启动/停止VWAP更新
    watch(() => backtestSettings.strategyType, (newStrategy, oldStrategy) => {
      if (oldStrategy === 'vwap') {
        stopVWAPDataUpdate()
      }
      
      if (newStrategy === 'vwap') {
        startVWAPDataUpdate()
      }
    })
    
    // 监听页面刷新和关闭事件，确保状态保存
    const setupPageStateHandlers = () => {
      // 监听页面刷新/关闭事件
      const handleBeforeUnload = (event) => {
        if (isVirtualTrading.value) {
          console.log('💾 页面即将关闭/刷新，保存虚拟交易状态')
          saveVirtualTradingState()
          
          // 在页面关闭时显示确认对话框
          const message = '虚拟交易正在运行中，确定要离开吗？状态已保存。'
          event.preventDefault()
          event.returnValue = message
          return message
        }
      }
      
      // 监听页面隐藏事件（切换标签页等）
      const handleVisibilityChange = () => {
        if (document.hidden && isVirtualTrading.value) {
          console.log('💾 页面隐藏，保存虚拟交易状态')
          saveVirtualTradingState()
        }
      }
      
      // 监听浏览器焦点丢失事件
      const handleBlur = () => {
        if (isVirtualTrading.value) {
          console.log('💾 浏览器失去焦点，保存虚拟交易状态')
          saveVirtualTradingState()
        }
      }
      
      // 添加事件监听器
      window.addEventListener('beforeunload', handleBeforeUnload)
      document.addEventListener('visibilitychange', handleVisibilityChange)
      window.addEventListener('blur', handleBlur)
      
      // 返回清理函数
      return () => {
        window.removeEventListener('beforeunload', handleBeforeUnload)
        document.removeEventListener('visibilitychange', handleVisibilityChange)
        window.removeEventListener('blur', handleBlur)
      }
    }
    const networkStatus = ref({
      online: navigator.onLine,
      lastSuccessTime: Date.now(),
      retryCount: 0,
      maxRetries: 5
    })
    
    // 监控网络状态变化
    const setupNetworkMonitoring = () => {
      window.addEventListener('online', () => {
        networkStatus.value.online = true
        networkStatus.value.retryCount = 0
        console.log('🟢 网络连接恢复')
        ElMessage({
          message: '网络连接恢复，虚拟交易继续运行',
          type: 'success'
        })
      })
      
      window.addEventListener('offline', () => {
        networkStatus.value.online = false
        console.log('🔴 网络连接中断')
        ElMessage({
          message: '网络连接中断，虚拟交易暂停',
          type: 'warning'
        })
      })
    }
    
    // 智能重试机制
    const smartRetry = async (operation, context = '') => {
      const maxRetries = networkStatus.value.maxRetries
      
      for (let i = 0; i < maxRetries; i++) {
        try {
          const result = await operation()
          networkStatus.value.lastSuccessTime = Date.now()
          networkStatus.value.retryCount = 0
          return result
        } catch (error) {
          networkStatus.value.retryCount = i + 1
          console.warn(`${context} 尝试 ${i + 1}/${maxRetries} 失败:`, error.message)
          
          if (i === maxRetries - 1) {
            console.error(`${context} 所有重试尝试均失败`)
            throw error
          }
          
          // 指数退避：1s, 2s, 4s, 8s
          const delay = Math.pow(2, i) * 1000
          console.log(`等待 ${delay}ms 后重试...`)
          await new Promise(resolve => setTimeout(resolve, delay))
        }
      }
    }
    const VIRTUAL_TRADING_STATE_KEY = 'crypto_bot_virtual_trading_state'
    
    // 优化后的状态保存（添加错误处理和数据验证）
    const saveVirtualTradingState = () => {
      try {
        // 数据验证
        if (!isVirtualTrading.value && virtualTradingResults.trades.length === 0) {
          console.log('没有需要保存的数据')
          return
        }
        
        const stateData = {
          isActive: isVirtualTrading.value,
          symbol: backtestSettings.symbol,
          strategy: backtestSettings.strategyType,
          startTime: new Date().toISOString(),
          cash: virtualTradingResults.cash,
          position: virtualTradingResults.position,
          totalValue: virtualTradingResults.totalValue,
          currentPrice: virtualTradingResults.currentPrice,
          pnl: virtualTradingResults.pnl,
          pnlPercent: virtualTradingResults.pnlPercent,
          trades: virtualTradingResults.trades,
          priceHistory: virtualTradingResults.priceHistory.slice(-50), // 只保存最近50个价格点
          lastSignalTime: virtualTradingResults.lastSignalTime,
          // 风险控制状态
          maxDrawdownReached: virtualTradingResults.maxDrawdownReached,
          currentDrawdown: virtualTradingResults.currentDrawdown,
          riskLocked: virtualTradingResults.riskLocked,
          lastStopLoss: virtualTradingResults.lastStopLoss,
          lastTakeProfit: virtualTradingResults.lastTakeProfit,
          positionValue: virtualTradingResults.positionValue,
          riskEvents: virtualTradingResults.riskEvents.slice(-10), // 只保存最近10个风险事件
          // 当前会话交易跟踪
          currentSessionTradesCount: virtualTradingResults.currentSessionTradesCount,
          sessionStartTime: virtualTradingResults.sessionStartTime,
          settings: {
            symbol: backtestSettings.symbol, // 添加交易对保存
            initialCapital: backtestSettings.initialCapital,
            tradeAmount: backtestSettings.tradeAmount,
            fastMAPeriod: backtestSettings.fastMAPeriod,
            slowMAPeriod: backtestSettings.slowMAPeriod,
            rsiPeriod: backtestSettings.rsiPeriod,
            overbought: backtestSettings.overbought,
            oversold: backtestSettings.oversold,
            bbPeriod: backtestSettings.bbPeriod,
            bbStdDev: backtestSettings.bbStdDev,
            stopLoss: backtestSettings.stopLoss,
            takeProfit: backtestSettings.takeProfit,
            maxPosition: backtestSettings.maxPosition,
            riskControl: backtestSettings.riskControl,
            maxDrawdownLimit: backtestSettings.maxDrawdownLimit,
            strategyType: backtestSettings.strategyType, // 添加策略类型保存
            period: backtestSettings.period, // 添加周期保存
            interval: backtestSettings.interval, // 添加K线周期保存
            dataSource: backtestSettings.dataSource, // 添加数据源保存
            // AI智能策略1参数
            mlConfidenceThreshold: backtestSettings.mlConfidenceThreshold,
            mlFeatureWeighting: backtestSettings.mlFeatureWeighting,
            mlMarketStateAware: backtestSettings.mlMarketStateAware,
            mlDynamicPositioning: backtestSettings.mlDynamicPositioning,
            mlSentimentWeight: backtestSettings.mlSentimentWeight,
            mlAdaptiveStopLoss: backtestSettings.mlAdaptiveStopLoss,
            // 新增高级AI参数
            mlRiskFilter: backtestSettings.mlRiskFilter,
            mlSignalThreshold: backtestSettings.mlSignalThreshold,
            mlMultiFactorMode: backtestSettings.mlMultiFactorMode
          },
          lastUpdated: new Date().toISOString(),
          version: '2.0' // 版本标识
        }
        
        // 检查数据大小（限制在5MB以内）
        const dataSize = JSON.stringify(stateData).length
        const maxSize = 5 * 1024 * 1024 // 5MB
        
        if (dataSize > maxSize) {
          console.warn(`状态数据过大（${(dataSize / 1024 / 1024).toFixed(2)}MB），精简数据`)
          // 精简数据
          stateData.trades = stateData.trades.slice(-100) // 只保存最近100笔交易
          stateData.priceHistory = stateData.priceHistory.slice(-30) // 只保存最近30个价格点
          stateData.riskEvents = stateData.riskEvents.slice(-5) // 只保存最近5个风险事件
        }
        
        localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(stateData))
        console.log(`✅ 虚拟交易状态已保存（${(dataSize / 1024).toFixed(1)}KB）`)
      } catch (error) {
        console.error('❌ 保存虚拟交易状态失败:', error)
        
        // 尝试清理旧数据后重试
        try {
          localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
          console.log('已清理旧状态数据')
        } catch (cleanupError) {
          console.error('清理旧状态数据失败:', cleanupError)
        }
        
        ElMessage({
          message: '保存虚拟交易状态失败，请检查浏览器存储空间',
          type: 'warning'
        })
      }
    }
    
    // 优化后的状态加载（添加版本兼容性和数据验证）
    const loadVirtualTradingState = () => {
      try {
        const stateJson = localStorage.getItem(VIRTUAL_TRADING_STATE_KEY)
        if (!stateJson) {
          console.log('⚠️ 未找到保存的虚拟交易状态')
          return null
        }
        
        const stateData = JSON.parse(stateJson)
        
        // 版本兼容性检查
        const version = stateData.version || '1.0'
        if (version !== '2.0') {
          console.log('旧版本数据，将进行升级')
          return migrateOldStateData(stateData)
        }
        
        // 验证状态数据完整性
        const requiredFields = ['isActive', 'symbol', 'strategy', 'cash', 'position', 'totalValue']
        const missingFields = requiredFields.filter(field => !(field in stateData))
        
        if (missingFields.length > 0) {
          console.error('❌ 状态数据不完整，缺少字段:', missingFields)
          return null
        }
        
        // 数据合理性检查
        if (stateData.cash < 0 || stateData.position < 0 || stateData.totalValue < 0) {
          console.error('❌ 状态数据包含负值，可能已损坏')
          return null
        }
        
        // 检查数据时效性（24小时内的数据才有效）
        const lastUpdated = new Date(stateData.lastUpdated)
        const now = new Date()
        const hoursDiff = (now - lastUpdated) / (1000 * 60 * 60)
        
        if (hoursDiff > 24) {
          console.log(`⚠️ 状态数据过旧（${hoursDiff.toFixed(1)}小时前），建议清理`)
          // 不返回null，但给出警告
        }
        
        console.log('✅ 虚拟交易状态加载成功')
        console.log(`📅 最后更新: ${stateData.lastUpdated}`)
        console.log(`💰 当前盈亏: ${stateData.pnlPercent?.toFixed(2) || 0}%`)
        return stateData
      } catch (error) {
        console.error('❌ 加载虚拟交易状态失败:', error)
        
        // 尝试清理损坏的数据
        try {
          localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
          console.log('已清理损坏的状态数据')
        } catch (cleanupError) {
          console.error('清理损坏数据失败:', cleanupError)
        }
        
        return null
      }
    }
    
    // 迁移旧版本数据
    const migrateOldStateData = (oldData) => {
      try {
        console.log('开始迁移旧版本数据...')
        
        const migratedData = {
          ...oldData,
          version: '2.0',
          // 添加新字段的默认值
          maxDrawdownReached: oldData.maxDrawdownReached || 0,
          currentDrawdown: oldData.currentDrawdown || 0,
          riskLocked: oldData.riskLocked || false,
          lastStopLoss: oldData.lastStopLoss || null,
          lastTakeProfit: oldData.lastTakeProfit || null,
          positionValue: oldData.positionValue || 0,
          riskEvents: oldData.riskEvents || [],
          settings: {
            ...oldData.settings,
            symbol: oldData.symbol || oldData.settings?.symbol || 'BTC/USDT', // 恢复交易对
            strategyType: oldData.strategy || oldData.settings?.strategyType || 'ma_cross', // 恢复策略类型
            period: oldData.settings?.period || '30d',
            interval: oldData.settings?.interval || '1d',
            dataSource: oldData.settings?.dataSource || 'real',
            maxPosition: oldData.settings?.maxPosition || 80,
            riskControl: oldData.settings?.riskControl !== undefined ? oldData.settings.riskControl : true,
            maxDrawdownLimit: oldData.settings?.maxDrawdownLimit || 15
          }
        }
        
        // 保存迁移后的数据
        localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(migratedData))
        console.log('✅ 数据迁移完成')
        
        return migratedData
      } catch (error) {
        console.error('❌ 数据迁移失败:', error)
        return null
      }
    }
    
    // 恢复虚拟交易状态
    const restoreVirtualTradingState = (stateData) => {
      try {
        // 恢复交易设置（包括交易对信息）
        if (stateData.settings) {
          Object.assign(backtestSettings, stateData.settings)
        }
        
        // 兼容性处理：从外层symbol字段恢复交易对（针对旧版本数据）
        if (stateData.symbol && !stateData.settings?.symbol) {
          backtestSettings.symbol = stateData.symbol
        }
        
        // 兼容性处理：从外层strategy字段恢复策略类型（针对旧版本数据）
        if (stateData.strategy && !stateData.settings?.strategyType) {
          backtestSettings.strategyType = stateData.strategy
        }
        
        console.log(`🔄 恢复交易对: ${backtestSettings.symbol}, 策略: ${backtestSettings.strategyType}`)
        
        // 恢复虚拟交易数据
        Object.assign(virtualTradingResults, {
          cash: stateData.cash || 0,
          position: stateData.position || 0,
          totalValue: stateData.totalValue || 0,
          currentPrice: stateData.currentPrice || 0,
          pnl: stateData.pnl || 0,
          pnlPercent: stateData.pnlPercent || 0,
          trades: stateData.trades || [],
          priceHistory: stateData.priceHistory || [],
          lastSignalTime: stateData.lastSignalTime || 0,
          // 恢复当前会话交易计数器（重新开始计数）
          currentSessionTradesCount: 0, // 重新开始计数当前会话
          sessionStartTime: new Date().toISOString() // 记录新会话开始时间
        })
        
        // 恢复虚拟交易状态
        if (stateData.isActive) {
          isVirtualTrading.value = true
          
          // 自动切换Binance图表到对应的交易对页面
          const binanceSymbolFormat = backtestSettings.symbol.replace('/', '')
          updateBinanceChart(binanceSymbolFormat)
          
          // 重新启动虚拟交易定时器
          virtualTradingInterval.value = setInterval(() => {
            updateVirtualTradingWithRealData()
          }, 5000)
          
          ElMessage({
            message: `虚拟交易状态已恢复，当前盈亏: ${stateData.pnlPercent.toFixed(2)}%`,
            type: 'success',
            duration: 4000
          })
          
          console.log('🔄 虚拟交易已恢复运行')
        }
        
        return true
      } catch (error) {
        console.error('❌ 恢复虚拟交易状态失败:', error)
        ElMessage({
          message: '恢复虚拟交易状态失败',
          type: 'error'
        })
        return false
      }
    }
    
    // 手动保存状态（用于调试和用户主动保存）
    const manualSaveState = () => {
      try {
        saveVirtualTradingState()
        ElMessage({
          message: '状态已手动保存成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        ElMessage({
          message: '手动保存状态失败: ' + error.message,
          type: 'error'
        })
      }
    }
    const clearVirtualTradingState = () => {
      try {
        localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
        console.log('🗑️ 虚拟交易状态已清理')
        ElMessage({
          message: '虚拟交易状态已清理',
          type: 'success'
        })
      } catch (error) {
        console.error('❌ 清理虚拟交易状态失败:', error)
      }
    }
    
    // 下载文件工具函数
    const downloadFile = (content, filename, mimeType = 'text/plain') => {
      try {
        // 创建 Blob 对象
        const blob = new Blob([content], { type: mimeType })
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = filename
        
        // 临时添加到 DOM 并触发下载
        document.body.appendChild(link)
        link.click()
        
        // 清理资源
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        console.log(`📁 文件下载成功: ${filename}`)
      } catch (error) {
        console.error('📁 文件下载失败:', error)
        throw new Error(`文件下载失败: ${error.message}`)
      }
    }

    // 导出虚拟交易数据
    const exportVirtualTradingData = () => {
      try {
        if (!virtualTradingResults.trades || virtualTradingResults.trades.length === 0) {
          ElMessage({
            message: '没有交易数据可导出',
            type: 'warning'
          })
          return
        }
        
        // 准备导出数据
        const exportData = {
          summary: {
            symbol: backtestSettings.symbol,
            strategy: backtestSettings.strategyType,
            initialCapital: backtestSettings.initialCapital,
            finalValue: virtualTradingResults.totalValue,
            totalPnL: virtualTradingResults.pnl,
            totalPnLPercent: virtualTradingResults.pnlPercent,
            totalTrades: virtualTradingResults.trades.length,
            exportTime: new Date().toISOString(),
            timePeriod: {
              start: virtualTradingResults.trades[0]?.date || 'N/A',
              end: virtualTradingResults.trades[virtualTradingResults.trades.length - 1]?.date || 'N/A'
            }
          },
          trades: virtualTradingResults.trades.map(trade => ({
            id: trade.id,
            date: trade.date,
            time: trade.time,
            type: trade.type,
            price: trade.price,
            amount: trade.amount,
            value: trade.value,
            profit: trade.profit || 0,
            reason: trade.reason,
            isRealTime: trade.isRealTime || false
          })),
          statistics: calculateVirtualTradingStatistics()
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19)
        const filename = `virtual_trading_${backtestSettings.symbol.replace('/', '')}_${timestamp}`
        
        // 导出JSON格式
        const jsonContent = JSON.stringify(exportData, null, 2)
        downloadFile(jsonContent, `${filename}.json`, 'application/json')
        
        // 导出CSV格式
        const csvContent = generateCSV(exportData.trades)
        downloadFile(csvContent, `${filename}_trades.csv`, 'text/csv')
        
        ElMessage({
          message: `交易数据已导出（JSON + CSV）`,
          type: 'success',
          duration: 3000
        })
        
      } catch (error) {
        console.error('导出虚拟交易数据失败:', error)
        ElMessage({
          message: '导出数据失败: ' + error.message,
          type: 'error'
        })
      }
    }
    
    // 生成CSV数据
    const generateCSV = (trades) => {
      const headers = [
        '交易ID', '日期', '时间', '类型', '价格', '数量', '价值', '盈亏', '原因', '实时数据'
      ]
      
      const csvRows = [
        headers.join(',')
      ]
      
      trades.forEach(trade => {
        const row = [
          trade.id,
          trade.date,
          trade.time,
          trade.type === 'buy' ? '买入' : '卖出',
          trade.price.toFixed(2),
          trade.amount.toFixed(6),
          trade.value.toFixed(2),
          (trade.profit || 0).toFixed(2),
          `"${trade.reason}"`, // 用引号包裹以防止CSV格式问题
          trade.isRealTime ? '是' : '否'
        ]
        csvRows.push(row.join(','))
      })
      
      return csvRows.join('\n')
    }
    
    // 计算虚拟交易统计数据
    const calculateVirtualTradingStatistics = () => {
      const trades = virtualTradingResults.trades
      if (!trades || trades.length === 0) {
        return {
          totalTrades: 0,
          winningTrades: 0,
          losingTrades: 0,
          winRate: 0,
          averageWin: 0,
          averageLoss: 0,
          profitFactor: 0,
          maxWin: 0,
          maxLoss: 0,
          maxDrawdown: 0,
          maxDrawdownPercent: 0,
          sharpeRatio: 0,
          totalReturn: virtualTradingResults.pnlPercent,
          tradingDays: 0
        }
      }
      
      // 基本统计
      const totalTrades = trades.length
      const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
      const winningTrades = sellTrades.filter(t => t.profit > 0)
      const losingTrades = sellTrades.filter(t => t.profit < 0)
      
      const winRate = sellTrades.length > 0 ? (winningTrades.length / sellTrades.length) * 100 : 0
      
      // 盈亏统计
      const totalWin = winningTrades.reduce((sum, t) => sum + t.profit, 0)
      const totalLoss = Math.abs(losingTrades.reduce((sum, t) => sum + t.profit, 0))
      const averageWin = winningTrades.length > 0 ? totalWin / winningTrades.length : 0
      const averageLoss = losingTrades.length > 0 ? totalLoss / losingTrades.length : 0
      const profitFactor = totalLoss > 0 ? totalWin / totalLoss : totalWin > 0 ? Infinity : 0
      
      const maxWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.profit)) : 0
      const maxLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.profit)) : 0
      
      // 计算最大回撤
      let maxDrawdown = 0
      let maxDrawdownPercent = 0
      let peak = backtestSettings.initialCapital
      let currentCapital = backtestSettings.initialCapital
      
      trades.forEach(trade => {
        if (trade.type === 'sell' && trade.profit !== undefined) {
          currentCapital += trade.profit
          if (currentCapital > peak) {
            peak = currentCapital
          } else {
            const drawdown = peak - currentCapital
            const drawdownPercent = (drawdown / peak) * 100
            if (drawdown > maxDrawdown) {
              maxDrawdown = drawdown
              maxDrawdownPercent = drawdownPercent
            }
          }
        }
      })
      
      // 计算交易天数
      const tradeDates = [...new Set(trades.map(t => t.date))]
      const tradingDays = tradeDates.length
      
      // 简化的夏普比率计算（假设无风险收益率3%）
      const riskFreeRate = 0.03
      const annualReturn = tradingDays > 0 ? (virtualTradingResults.pnlPercent / 100) * (365 / tradingDays) : 0
      const volatility = sellTrades.length > 1 ? 
        Math.sqrt(sellTrades.reduce((sum, t) => {
          const returnRate = t.profit / backtestSettings.initialCapital
          const avgReturn = (virtualTradingResults.pnl / backtestSettings.initialCapital) / sellTrades.length
          return sum + Math.pow(returnRate - avgReturn, 2)
        }, 0) / (sellTrades.length - 1)) * Math.sqrt(365) : 0
      
      const sharpeRatio = volatility > 0 ? (annualReturn - riskFreeRate) / volatility : 0
      
      return {
        totalTrades,
        winningTrades: winningTrades.length,
        losingTrades: losingTrades.length,
        winRate: parseFloat(winRate.toFixed(2)),
        averageWin: parseFloat(averageWin.toFixed(2)),
        averageLoss: parseFloat(averageLoss.toFixed(2)),
        profitFactor: parseFloat(profitFactor.toFixed(2)),
        maxWin: parseFloat(maxWin.toFixed(2)),
        maxLoss: parseFloat(maxLoss.toFixed(2)),
        maxDrawdown: parseFloat(maxDrawdown.toFixed(2)),
        maxDrawdownPercent: parseFloat(maxDrawdownPercent.toFixed(2)),
        sharpeRatio: parseFloat(sharpeRatio.toFixed(3)),
        totalReturn: parseFloat(virtualTradingResults.pnlPercent.toFixed(2)),
        tradingDays
      }
    }
    
    // 虚拟交易统计数据（响应式）
    const virtualTradingStatistics = computed(() => {
      return calculateVirtualTradingStatistics()
    })
    
    // 运行回测
    const runBacktest = async () => {
      try {
        isBacktesting.value = true
        backtestResults.value = { equityCurve: [], trades: [] }
        backtestTrades.value = []
        
        // 模拟获取历史数据
        const historicalData = await fetchHistoricalData(backtestSettings.symbol, backtestSettings.period, backtestSettings.interval)
        
        // 根据策略类型执行回测
        switch (backtestSettings.strategyType) {
          case 'ma_cross':
            backtestResults.value = runMACrossStrategy(historicalData)
            break
          case 'rsi':
            backtestResults.value = runRSIStrategy(historicalData)
            break
          case 'bollinger':
            backtestResults.value = runBollingerStrategy(historicalData)
            break
          case 'vwap':
            backtestResults.value = runVWAPStrategy(historicalData)
            break
          case 'custom':
            backtestResults.value = runCustomStrategy(historicalData)
            break
          case 'ml_strategy1':
            backtestResults.value = runMLStrategy1(historicalData)
            break
        }
        
        // 更新交易记录
        backtestTrades.value = backtestResults.value.trades || []
        
        // 计算回测结果
        calculateBacktestResults()
        
        // 等待DOM更新后绘制图表
        await nextTick()
        drawBacktestChart(backtestResults.value)
        
        ElMessage({
          message: '回测完成',
          type: 'success'
        })
      } catch (error) {
        console.error('回测失败:', error)
        ElMessage({
          message: '回测失败: ' + error.message,
          type: 'error'
        })
      } finally {
        isBacktesting.value = false
      }
    }
    
    // 启动虚拟交易
    const startVirtualTrading = async () => {
      try {
        if (isVirtualTrading.value) {
          // 停止虚拟交易
          stopVirtualTrading()
          return
        }
        
        // 检查是否有保存的状态
        const savedState = loadVirtualTradingState()
        
        if (savedState && savedState.isActive) {
          // 有保存的活跃状态，询问用户是否恢复
          const shouldRestore = await ElMessageBox.confirm(
            `检测到上次未完成的虚拟交易：\n` +
            `交易对: ${savedState.symbol}\n` +
            `策略: ${savedState.strategy}\n` +
            `当前盈亏: ${savedState.pnlPercent.toFixed(2)}%\n` +
            `交易次数: ${savedState.trades.length}\n\n` +
            `是否恢复上次的虚拟交易状态？`,
            '恢复虚拟交易',
            {
              confirmButtonText: '恢复继续',
              cancelButtonText: '重新开始',
              type: 'question'
            }
          ).catch(() => false)
          
          if (shouldRestore) {
            // 恢复之前的状态
            const restored = restoreVirtualTradingState(savedState)
            if (restored) {
              return
            }
          } else {
            // 用户选择重新开始，清理旧状态
            clearVirtualTradingState()
          }
        }
        
        // 新启动虚拟交易
        isVirtualTrading.value = true
        
        // 初始化虚拟账户
        Object.assign(virtualTradingResults, {
          cash: backtestSettings.initialCapital,
          position: 0,
          totalValue: backtestSettings.initialCapital,
          trades: [],
          currentPrice: 0,
          pnl: 0,
          pnlPercent: 0,
          priceHistory: [], // 用于存储价格历史计算技术指标
          lastSignalTime: 0, // 防止频繁交易
          lastUpdateTime: 0,
          priceCache: null,
          cacheExpiry: 0,
          // 风险控制相关
          maxDrawdownReached: 0,
          currentDrawdown: 0,
          riskLocked: false,
          lastStopLoss: null,
          lastTakeProfit: null,
          positionValue: 0,
          riskEvents: [],
          // 当前会话交易跟踪
          currentSessionTradesCount: 0,
          sessionStartTime: new Date().toISOString()
        })
        
        // 获取初始价格
        await fetchCurrentRealTimePrice()
        
        // 立即保存初始状态
        saveVirtualTradingState()
        
        // 自动切换Binance图表到对应的交易对页面
        const binanceSymbolFormat = backtestSettings.symbol.replace('/', '')
        updateBinanceChart(binanceSymbolFormat)
        
        ElMessage({
          message: `虚拟交易已启动，初始资金: $${backtestSettings.initialCapital.toLocaleString()}，使用上方市场数据，Binance图表已切换至${backtestSettings.symbol}`,
          type: 'success'
        })
        
        // 启动定时器，与上方数据刷新保持同步
        virtualTradingInterval.value = setInterval(() => {
          updateVirtualTradingWithRealData()
        }, 60000) // 每1分钟更新，与市场数据刷新同步
        
        // 如果使用VWAP策略，启动VWAP数据更新
        if (backtestSettings.strategyType === 'vwap') {
          startVWAPDataUpdate()
        }
        
      } catch (error) {
        console.error('启动虚拟交易失败:', error)
        ElMessage({
          message: '启动虚拟交易失败: ' + error.message,
          type: 'error'
        })
        isVirtualTrading.value = false
      }
    }
    
    // 获取实时K线数据（优化版）
    const fetchRealTimeKlineData = async (symbol, interval = '1m') => {
      try {
        // 检查缓存
        const cacheKey = `${symbol}_${interval}`
        const now = Date.now()
        
        // 如果缓存存在且未过期，直接返回缓存数据
        if (vwapDataCache.data[cacheKey] && 
            now - vwapDataCache.lastUpdate[cacheKey] < vwapDataCache.cacheExpiry) {
          console.log(`使用VWAP缓存数据: ${symbol}`)
          return vwapDataCache.data[cacheKey]
        }
        
        // 转换交易对格式
        const symbolMap = {
          'BTC/USDT': 'BTCUSDT',
          'ETH/USDT': 'ETHUSDT',
          'BNB/USDT': 'BNBUSDT',
          'SOL/USDT': 'SOLUSDT'
        }
        
        const binanceSymbol = symbolMap[symbol]
        if (!binanceSymbol) {
          throw new Error(`不支持的交易对: ${symbol}`)
        }
        
        // 调用Binance API获取K线数据
        const response = await axios.get('https://api.binance.com/api/v3/klines', {
          params: {
            symbol: binanceSymbol,
            interval: interval,
            limit: 100 // 获取最近100根K线
          },
          timeout: 10000
        })
        
        if (!response.data || !Array.isArray(response.data)) {
          throw new Error('无效的API响应')
        }
        
        // 转换数据格式
        const klineData = response.data.map(item => ({
          date: new Date(item[0]).toISOString(),
          open: parseFloat(item[1]),
          high: parseFloat(item[2]),
          low: parseFloat(item[3]),
          close: parseFloat(item[4]),
          volume: parseFloat(item[5]),
          timestamp: item[0]
        }))
        
        // 更新缓存
        vwapDataCache.data[cacheKey] = klineData
        vwapDataCache.lastUpdate[cacheKey] = now
        
        console.log(`获取到${klineData.length}条K线数据用于VWAP计算`)
        return klineData
        
      } catch (error) {
        console.error('获取K线数据失败:', error)
        throw error
      }
    }
    
    // 获取当前实时价格（优化版：优先使用Binance图表实时价格）
    const fetchCurrentRealTimePrice = async () => {
      try {
        // 检查网络状态
        if (!networkStatus.value.online) {
          throw new Error('网络连接不可用')
        }
        
        // 如果使用VWAP策略，直接从API获取价格
        if (backtestSettings.strategyType === 'vwap') {
          console.log('使用VWAP策略，直接从API获取价格')
          const klineData = await fetchRealTimeKlineData(backtestSettings.symbol, '1m')
          if (klineData && klineData.length > 0) {
            const latestData = klineData[klineData.length - 1]
            const price = latestData.close
            const now = Date.now()
            
            virtualTradingResults.priceCache = price
            virtualTradingResults.cacheExpiry = now + 60000 // VWAP策略数据缓存1分钟
            virtualTradingResults.currentPrice = price
            virtualTradingResults.lastUpdateTime = now
            
            // 更新价格历史（包含完整K线数据）
            const priceData = {
              date: latestData.date,
              time: new Date(latestData.timestamp).toLocaleTimeString(),
              close: price,
              high: latestData.high,
              low: latestData.low,
              volume: latestData.volume,
              timestamp: latestData.timestamp
            }
            
            // 添加到价格历史
            virtualTradingResults.priceHistory.push(priceData)
            
            // 保持最近100个价格数据点
            if (virtualTradingResults.priceHistory.length > 100) {
              virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
            }
            
            console.log(`📈 VWAP策略直接API获取价格: ${backtestSettings.symbol} = $${price.toFixed(2)}`)
            return price
          }
        }
        
        // 首先检查是否有Binance图表的实时价格数据（最高优先级）
        const currentVirtualSymbol = backtestSettings.symbol.replace('/', '')
        if (binanceSymbol.value === currentVirtualSymbol && binanceCurrentPrice.value > 0) {
          const price = binanceCurrentPrice.value
          const now = Date.now()
          
          virtualTradingResults.priceCache = price
          virtualTradingResults.cacheExpiry = now + 10000 // Binance图表数据更加实时，缓存10秒
          virtualTradingResults.currentPrice = price
          virtualTradingResults.lastUpdateTime = now
          
          // 添加到价格历史
          const nowDate = new Date(now)
          const priceData = {
            date: nowDate.toISOString().split('T')[0],
            time: nowDate.toLocaleTimeString(),
            close: price,
            timestamp: now
          }
          
          virtualTradingResults.priceHistory.push(priceData)
          
          // 保持最近100个价格数据点
          if (virtualTradingResults.priceHistory.length > 100) {
            virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
          }
          
          console.log(`⚡ 使用Binance图表实时价格: ${backtestSettings.symbol} = $${price.toFixed(2)}`)
          return price
        }
        
        // 其次使用上方市场概览中已获取的数据
        const currentOverview = marketOverview.find(item => item.name === backtestSettings.symbol)
        if (currentOverview && currentOverview.price !== '加载中...') {
          const price = parseFloat(currentOverview.price.replace(/,/g, ''))
          if (!isNaN(price) && price > 0) {
            const now = Date.now()
            virtualTradingResults.priceCache = price
            virtualTradingResults.cacheExpiry = now + 60000 // 使用已获取数据，缓存1分钟
            virtualTradingResults.currentPrice = price
            virtualTradingResults.lastUpdateTime = now
            
            // 添加到价格历史
            const nowDate = new Date(now)
            const priceData = {
              date: nowDate.toISOString().split('T')[0],
              time: nowDate.toLocaleTimeString(),
              close: price,
              timestamp: now
            }
            
            virtualTradingResults.priceHistory.push(priceData)
            
            // 保持最近100个价格数据点
            if (virtualTradingResults.priceHistory.length > 100) {
              virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
            }
            
            console.log(`✅ 使用市场概览数据: ${backtestSettings.symbol} = $${price}`)
            return price
          }
        }
        
        // 备用：尝试从比较数据中获取价格
        const symbolKey = backtestSettings.symbol
        const comparisonItem = comparisonData.find(item => item.symbol === symbolKey)
        if (comparisonItem) {
          // 优先使用Binance数据
          let price = null
          if (comparisonItem.binance && comparisonItem.binance.price !== '') {
            price = parseFloat(comparisonItem.binance.price.replace(/,/g, ''))
          } else if (comparisonItem.coingecko && comparisonItem.coingecko.price !== '') {
            price = parseFloat(comparisonItem.coingecko.price.replace(/,/g, ''))
          } else if (comparisonItem.cryptocompare && comparisonItem.cryptocompare.price !== '') {
            price = parseFloat(comparisonItem.cryptocompare.price.replace(/,/g, ''))
          }
          
          if (price && !isNaN(price) && price > 0) {
            const now = Date.now()
            virtualTradingResults.priceCache = price
            virtualTradingResults.cacheExpiry = now + 60000
            virtualTradingResults.currentPrice = price
            virtualTradingResults.lastUpdateTime = now
            
            console.log(`✅ 使用比较数据: ${symbolKey} = $${price}`)
            return price
          }
        }
        
        // 最后备用：如果以上数据都不可用，使用缓存数据
        if (virtualTradingResults.priceCache) {
          console.warn('✅ 使用缓存价格数据:', virtualTradingResults.priceCache)
          virtualTradingResults.currentPrice = virtualTradingResults.priceCache
          return virtualTradingResults.priceCache
        }
        
        throw new Error('无法从已有数据中获取价格，请等待数据更新')
        
      } catch (error) {
        console.warn('获取已有数据失败，尝试API备用方案:', error.message)
        
        // 紧急备用：直接调用API（仅在其他方式都失败时使用）
        return await fetchPriceFromAPI()
      }
    }
    
    // 紧急备用：直接API获取价格（仅在其他方式都失败时使用）
    const fetchPriceFromAPI = async () => {
      const symbolMap = {
        'BTC/USDT': 'BTCUSDT',
        'ETH/USDT': 'ETHUSDT', 
        'BNB/USDT': 'BNBUSDT',
        'SOL/USDT': 'SOLUSDT'
      }
      
      const binanceSymbol = symbolMap[backtestSettings.symbol]
      if (!binanceSymbol) {
        throw new Error(`不支持的交易对: ${backtestSettings.symbol}`)
      }
      
      try {
        const response = await axios.get('https://api.binance.com/api/v3/ticker/price', {
          params: { symbol: binanceSymbol },
          timeout: 5000
        })
        
        if (!response.data || !response.data.price) {
          throw new Error('无效的API响应数据')
        }
        
        const price = parseFloat(response.data.price)
        const now = Date.now()
        
        virtualTradingResults.priceCache = price
        virtualTradingResults.cacheExpiry = now + 8000
        virtualTradingResults.currentPrice = price
        virtualTradingResults.lastUpdateTime = now
        
        console.log(`⚠️ 紧急API获取: ${backtestSettings.symbol} = $${price}`)
        return price
        
      } catch (error) {
        console.error('紧急API也失败:', error.message)
        throw new Error('无法获取任何价格数据')
      }
    }
    
    // 使用实时数据更新虚拟交易（增强版：添加风险控制）
    const updateVirtualTradingWithRealData = async () => {
      try {
        // 获取最新价格
        await fetchCurrentRealTimePrice()
        
        // 更新账户信息
        updateVirtualAccount()
        
        // 立即保存状态（每次更新都保存）
        saveVirtualTradingState()
        
        // 检查风险控制状态
        if (backtestSettings.riskControl) {
          const riskCheck = checkRiskControl()
          if (!riskCheck.canTrade) {
            console.log('风险控制阻止交易:', riskCheck.reason)
            return
          }
        }
        
        // 检查止损止盈
        const stopOrder = checkStopLossAndTakeProfit()
        if (stopOrder) {
          executeVirtualTradeWithRealData(stopOrder)
          virtualTradingResults.lastSignalTime = Date.now()
          // 交易后立即保存状态
          saveVirtualTradingState()
          return
        }
        
        // 检查是否有足够的价格历史数据来计算技术指标
        if (virtualTradingResults.priceHistory.length < 20) {
          console.log(`正在积累价格数据... 当前: ${virtualTradingResults.priceHistory.length}/20`)
          return
        }
        
        // 防止频繁交易（30秒内不重复交易，避免过度交易）
        const now = Date.now()
        if (now - virtualTradingResults.lastSignalTime < 30000) {
          return
        }
        
        // 根据策略生成交易信号
        const signal = generateRealTimeVirtualTradingSignal()
        
        if (signal) {
          // 检查仓位限制
          if (signal.type === 'buy' && !checkPositionLimit()) {
            console.log('仓位限制阻止买入')
            return
          }
          
          executeVirtualTradeWithRealData(signal)
          virtualTradingResults.lastSignalTime = now
          
          // 在执行交易后立即保存状态
          saveVirtualTradingState()
        }
        
      } catch (error) {
        console.error('实时虚拟交易更新失败:', error)
        // 即使出错也保存当前状态
        saveVirtualTradingState()
      }
    }
    
    // 检查风险控制状态
    const checkRiskControl = () => {
      const currentDrawdownPercent = (virtualTradingResults.currentDrawdown / backtestSettings.initialCapital) * 100
      
      // 检查最大回撤限制
      if (currentDrawdownPercent > backtestSettings.maxDrawdownLimit) {
        if (!virtualTradingResults.riskLocked) {
          virtualTradingResults.riskLocked = true
          virtualTradingResults.riskEvents.push({
            type: 'MAX_DRAWDOWN_EXCEEDED',
            time: new Date().toLocaleString(),
            drawdown: currentDrawdownPercent,
            limit: backtestSettings.maxDrawdownLimit
          })
          
          ElNotification({
            title: '风险警告',
            message: `最大回撤超限（${currentDrawdownPercent.toFixed(2)}% > ${backtestSettings.maxDrawdownLimit}%），停止新的交易`,
            type: 'error',
            duration: 0 // 不自动关闭
          })
        }
        
        return {
          canTrade: false,
          reason: `最大回撤超限（${currentDrawdownPercent.toFixed(2)}%）`
        }
      }
      
      // 检查仓位集中度
      const positionPercent = (virtualTradingResults.positionValue / virtualTradingResults.totalValue) * 100
      if (positionPercent > backtestSettings.maxPosition) {
        return {
          canTrade: false,
          reason: `仓位过于集中（${positionPercent.toFixed(2)}%）`
        }
      }
      
      return { canTrade: true }
    }
    
    // 检查止损止盈
    const checkStopLossAndTakeProfit = () => {
      if (virtualTradingResults.position <= 0) return null
      
      const currentPrice = virtualTradingResults.currentPrice
      const lastBuyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
      
      if (!lastBuyTrade) return null
      
      const buyPrice = lastBuyTrade.price
      const stopLossPrice = buyPrice * (1 - backtestSettings.stopLoss / 100)
      const takeProfitPrice = buyPrice * (1 + backtestSettings.takeProfit / 100)
      
      // 检查止损
      if (currentPrice <= stopLossPrice) {
        virtualTradingResults.lastStopLoss = currentPrice
        return {
          type: 'sell',
          reason: `止损出局(价格: $${currentPrice.toFixed(2)}, 止损: $${stopLossPrice.toFixed(2)})`
        }
      }
      
      // 检查止盈
      if (currentPrice >= takeProfitPrice) {
        virtualTradingResults.lastTakeProfit = currentPrice
        return {
          type: 'sell',
          reason: `止盈出局(价格: $${currentPrice.toFixed(2)}, 止盈: $${takeProfitPrice.toFixed(2)})`
        }
      }
      
      return null
    }
    
    // 检查仓位限制
    const checkPositionLimit = () => {
      const tradePercent = backtestSettings.tradeAmount / 100
      const proposedTradeValue = virtualTradingResults.cash * tradePercent
      const currentPositionValue = virtualTradingResults.position * virtualTradingResults.currentPrice
      const totalPositionValue = currentPositionValue + proposedTradeValue
      const positionPercent = (totalPositionValue / virtualTradingResults.totalValue) * 100
      
      return positionPercent <= backtestSettings.maxPosition
    }
    const generateRealTimeVirtualTradingSignal = () => {
      const priceHistory = virtualTradingResults.priceHistory
      
      if (priceHistory.length < 20) return null
      
      // 根据选择的策略生成信号
      switch (backtestSettings.strategyType) {
        case 'ma_cross':
          return generateRealTimeMASignal(priceHistory)
        case 'rsi':
          return generateRealTimeRSISignal(priceHistory)
        case 'bollinger':
          return generateRealTimeBollingerSignal(priceHistory)
        case 'vwap':
          return generateRealTimeVWAPSignal(priceHistory, virtualTradingResults.position)
        case 'custom':
          return generateRealTimeCustomSignal(priceHistory)
        case 'ml_strategy1':
          return generateRealTimeMLStrategy1Signal(priceHistory)
        default:
          return null
      }
    }
    
    // 实时MA交叉信号
    const generateRealTimeMASignal = (priceHistory) => {
      const fastMA = backtestSettings.fastMAPeriod
      const slowMA = backtestSettings.slowMAPeriod
      
      if (priceHistory.length < slowMA) return null
      
      const prices = priceHistory.map(p => p.close)
      
      // 计算当前和上一个MA值
      const currentFastMA = prices.slice(-fastMA).reduce((a, b) => a + b, 0) / fastMA
      const currentSlowMA = prices.slice(-slowMA).reduce((a, b) => a + b, 0) / slowMA
      
      if (priceHistory.length < slowMA + 1) return null
      
      const prevFastMA = prices.slice(-(fastMA + 1), -1).reduce((a, b) => a + b, 0) / fastMA
      const prevSlowMA = prices.slice(-(slowMA + 1), -1).reduce((a, b) => a + b, 0) / slowMA
      
      // 金叉信号（买入）
      if (currentFastMA > currentSlowMA && prevFastMA <= prevSlowMA && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: 'MA金叉(实时)' }
      }
      
      // 死叉信号（卖出）
      if (currentFastMA < currentSlowMA && prevFastMA >= prevSlowMA && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: 'MA死叉(实时)' }
      }
      
      return null
    }
    
    // 实时RSI信号
    const generateRealTimeRSISignal = (priceHistory) => {
      const rsiPeriod = backtestSettings.rsiPeriod
      const overbought = backtestSettings.overbought
      const oversold = backtestSettings.oversold
      
      if (priceHistory.length < rsiPeriod + 1) return null
      
      // 计算RSI
      const prices = priceHistory.slice(-rsiPeriod - 1).map(p => p.close)
      let gains = 0, losses = 0
      
      for (let i = 1; i < prices.length; i++) {
        const change = prices[i] - prices[i - 1]
        if (change > 0) gains += change
        else losses += Math.abs(change)
      }
      
      const avgGain = gains / rsiPeriod
      const avgLoss = losses / rsiPeriod
      
      if (avgLoss === 0) return null
      
      const rs = avgGain / avgLoss
      const currentRSI = 100 - (100 / (1 + rs))
      
      // 计算前一个RSI
      const prevPrices = priceHistory.slice(-rsiPeriod - 2, -1).map(p => p.close)
      let prevGains = 0, prevLosses = 0
      
      for (let i = 1; i < prevPrices.length; i++) {
        const change = prevPrices[i] - prevPrices[i - 1]
        if (change > 0) prevGains += change
        else prevLosses += Math.abs(change)
      }
      
      const prevAvgGain = prevGains / rsiPeriod
      const prevAvgLoss = prevLosses / rsiPeriod
      const prevRS = prevAvgLoss === 0 ? 0 : prevAvgGain / prevAvgLoss
      const prevRSI = 100 - (100 / (1 + prevRS))
      
      // RSI从超卖区域上穿（买入）
      if (prevRSI <= oversold && currentRSI > oversold && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: `RSI超卖反弹(实时-${currentRSI.toFixed(1)})` }
      }
      
      // RSI从超买区域下穿（卖出）
      if (prevRSI >= overbought && currentRSI < overbought && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: `RSI超买回落(实时-${currentRSI.toFixed(1)})` }
      }
      
      return null
    }
    
    // 实时布林带信号
    const generateRealTimeBollingerSignal = (priceHistory) => {
      const bbPeriod = backtestSettings.bbPeriod
      const bbStdDev = backtestSettings.bbStdDev
      
      if (priceHistory.length < bbPeriod) return null
      
      const prices = priceHistory.slice(-bbPeriod).map(p => p.close)
      const middle = prices.reduce((a, b) => a + b, 0) / prices.length
      const stdDev = Math.sqrt(prices.map(x => Math.pow(x - middle, 2)).reduce((a, b) => a + b, 0) / prices.length)
      
      const upper = middle + (stdDev * bbStdDev)
      const lower = middle - (stdDev * bbStdDev)
      
      const currentPrice = priceHistory[priceHistory.length - 1].close
      
      // 价格触及下轨（买入）
      if (currentPrice <= lower && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格触及布林带下轨(实时)' }
      }
      
      // 价格触及上轨（卖出）
      if (currentPrice >= upper && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格触及布林带上轨(实时)' }
      }
      
      return null
    }
    
    // 实时自定义信号
    const generateRealTimeCustomSignal = (priceHistory) => {
      if (priceHistory.length < 5) return null
      
      const currentPrice = priceHistory[priceHistory.length - 1].close
      const recentPrices = priceHistory.slice(-5).map(p => p.close)
      const avgPrice = recentPrices.reduce((a, b) => a + b, 0) / 5
      
      // 价格突破平均线2%（买入）
      if (currentPrice > avgPrice * 1.02 && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格突破(实时)' }
      }
      
      // 价格跌破平均线2%（卖出）
      if (currentPrice < avgPrice * 0.98 && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格跌破止损(实时)' }
      }
      
      return null
    }
    
    // 执行实时虚拟交易
    const executeVirtualTradeWithRealData = (signal) => {
      const currentPrice = virtualTradingResults.currentPrice
      const tradePercent = backtestSettings.tradeAmount / 100
      const timestamp = new Date().toLocaleTimeString()
      const now = new Date()
      
      if (signal.type === 'buy' && virtualTradingResults.position === 0) {
        // 买入
        const tradeAmount = virtualTradingResults.cash * tradePercent
        const shares = tradeAmount / currentPrice
        
        virtualTradingResults.cash -= tradeAmount
        virtualTradingResults.position = shares
        
        const trade = {
          id: Date.now(),
          type: 'buy',
          price: currentPrice,
          amount: shares,
          value: tradeAmount,
          reason: signal.reason,
          time: timestamp,
          date: now.toISOString().split('T')[0],
          isRealTime: true
        }
        
        virtualTradingResults.trades.push(trade)
        
        // 增加当前会话交易计数
        virtualTradingResults.currentSessionTradesCount++
        
        // 交易后立即保存状态
        saveVirtualTradingState()
        
        ElNotification({
          title: '实时虚拟交易 - 买入',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 数量: ${shares.toFixed(4)}`,
          type: 'success',
          duration: 4000
        })
        
      } else if (signal.type === 'sell' && virtualTradingResults.position > 0) {
        // 卖出
        const sellValue = virtualTradingResults.position * currentPrice
        const buyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        const profit = buyTrade ? sellValue - (virtualTradingResults.position * buyTrade.price) : 0
        
        virtualTradingResults.cash += sellValue
        
        const trade = {
          id: Date.now(),
          type: 'sell',
          price: currentPrice,
          amount: virtualTradingResults.position,
          value: sellValue,
          profit: profit,
          reason: signal.reason,
          time: timestamp,
          date: now.toISOString().split('T')[0],
          isRealTime: true
        }
        
        virtualTradingResults.trades.push(trade)
        virtualTradingResults.position = 0
        
        // 增加当前会话交易计数
        virtualTradingResults.currentSessionTradesCount++
        
        // 交易后立即保存状态
        saveVirtualTradingState()
        
        ElNotification({
          title: '实时虚拟交易 - 卖出',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 盈亏: $${profit.toFixed(2)}`,
          type: profit >= 0 ? 'success' : 'warning',
          duration: 4000
        })
      }
    }
    
    // 启动VWAP定时更新
    const startVWAPDataUpdate = () => {
      // 清除现有定时器
      if (vwapInterval.value) {
        clearInterval(vwapInterval.value)
      }
      
      // 每分钟获取一次数据
      vwapInterval.value = setInterval(async () => {
        try {
          const currentSymbol = backtestSettings.symbol
          console.log(`定时获取${currentSymbol}的K线数据用于VWAP计算`)
          
          // 获取实时K线数据
          const klineData = await fetchRealTimeKlineData(currentSymbol, '1m')
          
          // 计算并更新VWAP
          const vwapValues = calculateVWAP(klineData)
          
          // 存储到价格历史中供信号生成使用
          // 更新最新的价格历史数据
          const latestData = klineData.slice(-20) // 只取最近20条
          virtualTradingResults.priceHistory = [
            ...latestData.map(item => ({
              date: item.date,
              time: new Date(item.timestamp).toLocaleTimeString(),
              close: item.close,
              high: item.high,
              low: item.low,
              volume: item.volume,
              timestamp: item.timestamp
            }))
          ]
          
          console.log(`VWAP定时更新完成: ${vwapValues.length}条数据`)
        } catch (error) {
          console.error('VWAP定时更新失败:', error)
        }
      }, 60000) // 每分钟执行一次
      
      console.log('VWAP定时更新已启动')
    }
    
    // 停止VWAP定时更新
    const stopVWAPDataUpdate = () => {
      if (vwapInterval.value) {
        clearInterval(vwapInterval.value)
        vwapInterval.value = null
        console.log('VWAP定时更新已停止')
      }
    }
    
    // 停止虚拟交易
    const stopVirtualTrading = () => {
      if (virtualTradingInterval.value) {
        clearInterval(virtualTradingInterval.value)
        virtualTradingInterval.value = null
      }
      
      // 保存当前状态在停止之前
      if (isVirtualTrading.value) {
        saveVirtualTradingState()
      }
      
      isVirtualTrading.value = false
      
      if (virtualTradingResults.trades.length > 0) {
        ElMessage({
          message: `虚拟交易已停止，总交易次数: ${virtualTradingResults.trades.length}，盈亏: ${virtualTradingResults.pnlPercent.toFixed(2)}%，状态已保存`,
          type: 'info',
          duration: 4000
        })
      } else {
        ElMessage({
          message: '虚拟交易已停止，状态已保存',
          type: 'info'
        })
      }
    }
    
    // 更新虚拟交易（已弃用，由updateVirtualTradingWithRealData替代）
    const updateVirtualTrading = () => {
      console.warn('updateVirtualTrading已弃用，虚拟交易现在使用实时数据')
      // 这个函数保留用于兼容性，但不再使用历史数据
      // 实际的虚拟交易逻辑已移动到updateVirtualTradingWithRealData
    }
    
    // 生成虚拟交易信号
    const generateVirtualTradingSignal = () => {
      const currentIndex = virtualCurrentIndex.value
      const data = virtualTradingData.value
      
      if (currentIndex < 20) return null // 需要足够的历史数据
      
      // 根据选择的策略生成信号
      switch (backtestSettings.strategyType) {
        case 'ma_cross':
          return generateMASignal(data, currentIndex)
        case 'rsi':
          return generateRSISignal(data, currentIndex)
        case 'bollinger':
          return generateBollingerSignal(data, currentIndex)
        case 'vwap':
          return generateVWAPSignal(data, currentIndex, virtualTradingResults.position)
        case 'custom':
          return generateCustomSignal(data, currentIndex)
        case 'ml_strategy1':
          return generateMLStrategy1Signal(data, currentIndex)
        default:
          return null
      }
    }
    
    // MA交叉信号
    const generateMASignal = (data, currentIndex) => {
      const fastMA = backtestSettings.fastMAPeriod
      const slowMA = backtestSettings.slowMAPeriod
      
      if (currentIndex < slowMA) return null
      
      // 计算当前和上一个MA值
      const currentFastMA = calculateMA(data.slice(currentIndex - fastMA + 1, currentIndex + 1), fastMA)[0]
      const currentSlowMA = calculateMA(data.slice(currentIndex - slowMA + 1, currentIndex + 1), slowMA)[0]
      const prevFastMA = calculateMA(data.slice(currentIndex - fastMA, currentIndex), fastMA)[0]
      const prevSlowMA = calculateMA(data.slice(currentIndex - slowMA, currentIndex), slowMA)[0]
      
      // 金叉信号（买入）
      if (currentFastMA > currentSlowMA && prevFastMA <= prevSlowMA && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: 'MA金叉' }
      }
      
      // 死叉信号（卖出）
      if (currentFastMA < currentSlowMA && prevFastMA >= prevSlowMA && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: 'MA死叉' }
      }
      
      return null
    }
    
    // RSI信号
    const generateRSISignal = (data, currentIndex) => {
      const rsiPeriod = backtestSettings.rsiPeriod
      const overbought = backtestSettings.overbought
      const oversold = backtestSettings.oversold
      
      if (currentIndex < rsiPeriod + 1) return null
      
      const rsiData = data.slice(Math.max(0, currentIndex - rsiPeriod - 10), currentIndex + 1)
      const rsiValues = calculateRSI(rsiData, rsiPeriod)
      
      if (rsiValues.length < 2) return null
      
      const currentRSI = rsiValues[rsiValues.length - 1]
      const prevRSI = rsiValues[rsiValues.length - 2]
      
      // RSI从超卖区域上穿（买入）
      if (prevRSI <= oversold && currentRSI > oversold && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: `RSI超卖反弹(${currentRSI.toFixed(1)})` }
      }
      
      // RSI从超买区域下穿（卖出）
      if (prevRSI >= overbought && currentRSI < overbought && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: `RSI超买回落(${currentRSI.toFixed(1)})` }
      }
      
      return null
    }
    
    // 布林带信号
    const generateBollingerSignal = (data, currentIndex) => {
      const bbPeriod = backtestSettings.bbPeriod
      const bbStdDev = backtestSettings.bbStdDev
      
      if (currentIndex < bbPeriod) return null
      
      const recentData = data.slice(currentIndex - bbPeriod + 1, currentIndex + 1)
      const prices = recentData.map(d => d.close)
      const middle = prices.reduce((a, b) => a + b, 0) / prices.length
      const stdDev = Math.sqrt(prices.map(x => Math.pow(x - middle, 2)).reduce((a, b) => a + b, 0) / prices.length)
      
      const upper = middle + (stdDev * bbStdDev)
      const lower = middle - (stdDev * bbStdDev)
      
      const currentPrice = data[currentIndex].close
      
      // 价格触及下轨（买入）
      if (currentPrice <= lower && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格触及布林带下轨' }
      }
      
      // 价格触及上轨（卖出）
      if (currentPrice >= upper && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格触及布林带上轨' }
      }
      
      return null
    }
    
    // 自定义信号
    const generateCustomSignal = (data, currentIndex) => {
      // 简单的价格突破策略
      if (currentIndex < 5) return null
      
      const currentPrice = data[currentIndex].close
      const currentVolume = data[currentIndex].volume
      const recentData = data.slice(currentIndex - 5, currentIndex)
      const avgPrice = recentData.reduce((sum, d) => sum + d.close, 0) / 5
      const avgVolume = recentData.reduce((sum, d) => sum + d.volume, 0) / 5
      
      // 价格突破 + 成交量放大（买入）
      if (currentPrice > avgPrice * 1.02 && currentVolume > avgVolume * 1.5 && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格突破+量能放大' }
      }
      
      // 价格跌破（卖出）
      if (currentPrice < avgPrice * 0.98 && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格跌破止损' }
      }
      
      return null
    }
    
    // 执行虚拟交易
    const executeVirtualTrade = (signal, currentData) => {
      const currentPrice = currentData.close
      const tradePercent = backtestSettings.tradeAmount / 100
      const timestamp = new Date().toLocaleTimeString()
      
      if (signal.type === 'buy' && virtualTradingResults.position === 0) {
        // 买入
        const tradeAmount = virtualTradingResults.cash * tradePercent
        const shares = tradeAmount / currentPrice
        
        virtualTradingResults.cash -= tradeAmount
        virtualTradingResults.position = shares
        
        const trade = {
          id: Date.now(),
          type: 'buy',
          price: currentPrice,
          amount: shares,
          value: tradeAmount,
          reason: signal.reason,
          time: timestamp,
          date: currentData.date
        }
        
        virtualTradingResults.trades.push(trade)
        
        ElNotification({
          title: '虚拟交易 - 买入',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 数量: ${shares.toFixed(4)}`,
          type: 'success',
          duration: 3000
        })
        
      } else if (signal.type === 'sell' && virtualTradingResults.position > 0) {
        // 卖出
        const sellValue = virtualTradingResults.position * currentPrice
        const buyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        const profit = buyTrade ? sellValue - (virtualTradingResults.position * buyTrade.price) : 0
        
        virtualTradingResults.cash += sellValue
        
        const trade = {
          id: Date.now(),
          type: 'sell',
          price: currentPrice,
          amount: virtualTradingResults.position,
          value: sellValue,
          profit: profit,
          reason: signal.reason,
          time: timestamp,
          date: currentData.date
        }
        
        virtualTradingResults.trades.push(trade)
        virtualTradingResults.position = 0
        
        ElNotification({
          title: '虚拟交易 - 卖出',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 盈亏: $${profit.toFixed(2)}`,
          type: profit >= 0 ? 'success' : 'warning',
          duration: 3000
        })
      }
    }
    
    // 更新虚拟账户（增强版：添加风险管理）
    const updateVirtualAccount = () => {
      const positionValue = virtualTradingResults.position * virtualTradingResults.currentPrice
      const currentValue = virtualTradingResults.cash + positionValue
      
      virtualTradingResults.positionValue = positionValue
      virtualTradingResults.totalValue = currentValue
      virtualTradingResults.pnl = currentValue - backtestSettings.initialCapital
      virtualTradingResults.pnlPercent = (virtualTradingResults.pnl / backtestSettings.initialCapital) * 100
      
      // 计算当前回撤
      if (!virtualTradingResults.maxValue) {
        virtualTradingResults.maxValue = currentValue
      }
      
      if (currentValue > virtualTradingResults.maxValue) {
        virtualTradingResults.maxValue = currentValue
        virtualTradingResults.currentDrawdown = 0
      } else {
        virtualTradingResults.currentDrawdown = virtualTradingResults.maxValue - currentValue
        const drawdownPercent = (virtualTradingResults.currentDrawdown / virtualTradingResults.maxValue) * 100
        
        if (virtualTradingResults.currentDrawdown > virtualTradingResults.maxDrawdownReached) {
          virtualTradingResults.maxDrawdownReached = virtualTradingResults.currentDrawdown
        }
      }
    }
    
    // 获取历史数据
    const fetchHistoricalData = async (symbol, period, interval) => {
      // 根据用户选择决定使用真实数据还是模拟数据
      if (backtestSettings.dataSource === 'real') {
        try {
          // 尝试获取真实历史数据
          const realData = await fetchRealHistoricalData(symbol, period, interval)
          if (realData && realData.length > 0) {
            ElMessage({
              message: `成功获取${realData.length}条真实历史数据`,
              type: 'success'
            })
            return realData
          }
        } catch (error) {
          console.warn('获取真实数据失败，使用模拟数据:', error.message)
          ElMessage({
            message: '获取真实数据失败，使用模拟数据进行回测',
            type: 'warning'
          })
        }
      }
      
      // 使用模拟数据
      ElMessage({
        message: `使用模拟数据进行回测`,
        type: 'info'
      })
      return generateMockHistoricalData(symbol, period, interval)
    }
    
    // 获取真实历史数据
    const fetchRealHistoricalData = async (symbol, period, interval) => {
      const symbolMap = {
        'BTC/USDT': { binance: 'BTCUSDT', coingecko: 'bitcoin', cryptocompare: 'BTC' },
        'ETH/USDT': { binance: 'ETHUSDT', coingecko: 'ethereum', cryptocompare: 'ETH' },
        'BNB/USDT': { binance: 'BNBUSDT', coingecko: 'binancecoin', cryptocompare: 'BNB' },
        'SOL/USDT': { binance: 'SOLUSDT', coingecko: 'solana', cryptocompare: 'SOL' }
      }
      
      const coinInfo = symbolMap[symbol]
      if (!coinInfo) {
        throw new Error(`不支持的交易对: ${symbol}`)
      }
      
      // 转换周期为天数
      let days = 30
      if (period === '7d') days = 7
      else if (period === '30d') days = 30
      else if (period === '90d') days = 90
      else if (period === '1y') days = 365
      
      // 转换时间间隔
      let binanceInterval = '1d'
      if (interval === '1h') binanceInterval = '1h'
      else if (interval === '4h') binanceInterval = '4h'
      else if (interval === '1d') binanceInterval = '1d'
      
      // 优先使用Binance API（数据质量最高）
      try {
        ElMessage({
          message: '正在从 Binance 获取历史数据...',
          type: 'info',
          duration: 2000
        })
        
        const response = await axios.get('https://api.binance.com/api/v3/klines', {
          params: {
            symbol: coinInfo.binance,
            interval: binanceInterval,
            limit: Math.min(days, 1000) // Binance最多返回1000条数据
          },
          timeout: 15000
        })
        
        if (response.data && response.data.length > 0) {
          const data = response.data.map(item => ({
            date: new Date(item[0]).toISOString().split('T')[0],
            open: parseFloat(item[1]),
            high: parseFloat(item[2]),
            low: parseFloat(item[3]),
            close: parseFloat(item[4]),
            volume: parseFloat(item[5])
          }))
          
          console.log(`成功从 Binance 获取 ${data.length} 条数据`)
          return data
        }
      } catch (error) {
        console.warn('Binance API失败:', error.message)
        ElMessage({
          message: `Binance API 访问失败: ${error.message}`,
          type: 'warning',
          duration: 3000
        })
      }
      
      // 备用：CryptoCompare API
      try {
        ElMessage({
          message: '正在从 CryptoCompare 获取历史数据...',
          type: 'info',
          duration: 2000
        })
        
        const response = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
          params: {
            fsym: coinInfo.cryptocompare,
            tsym: 'USD',
            limit: Math.min(days, 2000)
          },
          timeout: 15000
        })
        
        if (response.data && response.data.Data && response.data.Data.Data) {
          const data = response.data.Data.Data.map(item => ({
            date: new Date(item.time * 1000).toISOString().split('T')[0],
            open: item.open,
            high: item.high,
            low: item.low,
            close: item.close,
            volume: item.volumeto
          }))
          
          console.log(`成功从 CryptoCompare 获取 ${data.length} 条数据`)
          return data
        }
      } catch (error) {
        console.warn('CryptoCompare API失败:', error.message)
        ElMessage({
          message: `CryptoCompare API 访问失败: ${error.message}`,
          type: 'warning',
          duration: 3000
        })
      }
      
      // 备用：CoinGecko API
      try {
        const response = await axios.get(`https://api.coingecko.com/api/v3/coins/${coinInfo.coingecko}/market_chart`, {
          params: {
            vs_currency: 'usd',
            days: days,
            interval: days > 90 ? 'daily' : 'daily'
          },
          timeout: 10000
        })
        
        if (response.data && response.data.prices) {
          return response.data.prices.map((item, index) => {
            const date = new Date(item[0]).toISOString().split('T')[0]
            const price = item[1]
            // CoinGecko只提供价格，我们需要模拟OHLC
            const variation = 0.02 // 2%的变化范围
            return {
              date,
              open: price * (1 + (Math.random() - 0.5) * variation),
              high: price * (1 + Math.random() * variation),
              low: price * (1 - Math.random() * variation),
              close: price,
              volume: 1000 + Math.random() * 2000
            }
          })
        }
      } catch (error) {
        console.warn('CoinGecko API失败:', error.message)
      }
      
      throw new Error('所有真实数据源都无法访问')
    }
    
    // 生成模拟历史数据（备用）
    const generateMockHistoricalData = (symbol, period, interval) => {
      const data = []
      const now = new Date()
      let days = 30
      
      if (period === '7d') days = 7
      else if (period === '30d') days = 30
      else if (period === '90d') days = 90
      else if (period === '1y') days = 365
      
      const basePrice = symbol === 'BTC/USDT' ? 45000 : 
                       symbol === 'ETH/USDT' ? 3000 : 
                       symbol === 'BNB/USDT' ? 400 : 150
      
      let currentPrice = basePrice
      let trend = 1 // 1为上涨趋势，-1为下跌趋势
      let trendDays = 0
      
      for (let i = 0; i < days; i++) {
        const date = new Date(now)
        date.setDate(date.getDate() - (days - i))
        
        // 每5-10天改变一次趋势
        if (trendDays > 5 + Math.random() * 5) {
          trend *= -1
          trendDays = 0
        }
        
        // 根据趋势调整价格
        const trendChange = trend * (0.005 + Math.random() * 0.015) // 0.5-2%的趋势变化
        const randomChange = (Math.random() - 0.5) * 0.01 // ±0.5%的随机波动
        
        currentPrice *= (1 + trendChange + randomChange)
        
        const open = currentPrice * (0.99 + Math.random() * 0.02)
        const close = currentPrice
        const high = Math.max(open, close) * (1 + Math.random() * 0.01)
        const low = Math.min(open, close) * (1 - Math.random() * 0.01)
        const volume = 500 + Math.random() * 1000
        
        data.push({
          date: date.toISOString().split('T')[0],
          open,
          high,
          low,
          close,
          volume
        })
        
        trendDays++
      }
      
      return data
    }
    

    

    

    

    

    

    

    
    // AI智能策略1 - 基于机器学习的多因子量化交易策略（优化版）
    const runMLStrategy1 = (data) => {
      const results = {
        equityCurve: [],
        trades: [],
        signals: [], // 新增：记录信号强度
        performance: {} // 新增：性能指标
      }
      
      const capital = backtestSettings.initialCapital
      const baseTradePercent = backtestSettings.tradeAmount / 100
      
      let position = 0
      let cash = capital
      let lastBuyPrice = 0
      let marketState = 'neutral'
      let consecutiveLosses = 0 // 新增：连续亏损计数
      let maxEquity = capital // 新增：最高权益记录
      
      const minDataPoints = Math.max(100, data.length * 0.15) // 优化：增加最小数据点
      
      for (let i = Math.floor(minDataPoints); i < data.length; i++) {
        const currentPrice = data[i].close
        const currentDate = data[i].date
        
        const features = calculateMLFeatures(data, i)
        if (!features) continue
        
        if (backtestSettings.mlMarketStateAware) {
          marketState = identifyMarketState(data, i)
        }
        
        const mlPrediction = performMLPrediction(features, marketState)
        
        // 记录信号强度用于分析
        results.signals.push({
          date: currentDate,
          signal: mlPrediction.signal,
          confidence: mlPrediction.confidence,
          marketState: marketState,
          price: currentPrice
        })
        
        let dynamicTradePercent = baseTradePercent
        if (backtestSettings.mlDynamicPositioning) {
          dynamicTradePercent = calculateDynamicPosition(features, mlPrediction, baseTradePercent, consecutiveLosses)
        }
        
        const adaptiveStopLoss = calculateAdaptiveStopLoss(features.atr, backtestSettings.mlAdaptiveStopLoss)
        const adaptiveTakeProfit = calculateAdaptiveTakeProfit(features.atr, mlPrediction.confidence)
        
        // 优化：添加风险过滤器
        const riskFilter = evaluateRiskConditions(features, marketState, consecutiveLosses, cash, capital)
        
        const buySignal = mlPrediction.signal === 'buy' && 
                         mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
                         position === 0 && 
                         riskFilter.allowBuy // 新增风险过滤
        
        const sellSignal = (mlPrediction.signal === 'sell' && 
                           mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold) ||
                          checkMLStopConditions(currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) ||
                          riskFilter.forceSell // 新增强制卖出条件
        
        if (buySignal && cash > 0) {
          const tradeValue = cash * (dynamicTradePercent / 100)
          const amount = tradeValue / currentPrice
          position = amount
          cash -= tradeValue
          lastBuyPrice = currentPrice
          consecutiveLosses = 0 // 重置连续亏损计数
          
          results.trades.push({
            date: currentDate,
            type: 'buy',
            price: currentPrice,
            amount: amount,
            value: tradeValue,
            reason: `ML信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState},动态仓位:${dynamicTradePercent.toFixed(1)}%)`
          })
        } else if (sellSignal && position > 0) {
          const sellAmount = position
          const tradeValue = sellAmount * currentPrice
          const profit = tradeValue - (sellAmount * lastBuyPrice)
          cash += tradeValue
          position = 0
          
          // 更新连续亏损计数
          if (profit < 0) {
            consecutiveLosses++
          } else {
            consecutiveLosses = 0
          }
          
          const sellReason = mlPrediction.signal === 'sell' ? 
            `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%)` :
            riskFilter && riskFilter.forceSell ? '风险控制强制卖出' :
            `智能止损止盈(ATR:${features.atr.toFixed(2)})`
          
          results.trades.push({
            date: currentDate,
            type: 'sell',
            price: currentPrice,
            amount: sellAmount,
            value: tradeValue,
            profit: profit,
            reason: sellReason
          })
        }
        
        const totalEquity = cash + (position * currentPrice)
        
        // 更新最高权益
        if (totalEquity > maxEquity) {
          maxEquity = totalEquity
        }
        
        results.equityCurve.push({
          date: currentDate,
          equity: totalEquity,
          drawdown: ((maxEquity - totalEquity) / maxEquity * 100).toFixed(2) // 记录回撤
        })
      }
      
      // 计算策略性能指标
      results.performance = calculateStrategyPerformance(results)
      
      return results
    }
    
    // ML特征计算函数
    const calculateMLFeatures = (data, index) => {
      if (index < 50) return null
      
      const currentData = data.slice(Math.max(0, index - 49), index + 1)
      const prices = currentData.map(d => d.close)
      const volumes = currentData.map(d => d.volume)
      const highs = currentData.map(d => d.high)
      const lows = currentData.map(d => d.low)
      
      const ma5 = calculateSMA(prices, 5)
      const ma10 = calculateSMA(prices, 10)
      const ma20 = calculateSMA(prices, 20)
      const ma50 = calculateSMA(prices, 50)
      
      const rsi = calculateRSI(currentData, 14)
      const macd = calculateMACD(prices)
      const bb = calculateBB(prices, 20, 2)
      const atr = calculateATR(currentData, 14)
      
      const volumeMA = calculateSMA(volumes, 20)
      const volumeRatio = volumes[volumes.length - 1] / (volumeMA[volumeMA.length - 1] || 1)
      
      const momentum = (prices[prices.length - 1] - prices[prices.length - 10]) / prices[prices.length - 10]
      const volatility = calculateVolatility(prices, 20)
      const supportResistance = calculateSupportResistance(currentData)
      
      return {
        price: prices[prices.length - 1],
        ma5: ma5[ma5.length - 1],
        ma10: ma10[ma10.length - 1],
        ma20: ma20[ma20.length - 1],
        ma50: ma50[ma50.length - 1],
        rsi: rsi[rsi.length - 1],
        macd_line: macd.macd[macd.macd.length - 1],
        macd_signal: macd.signal[macd.signal.length - 1],
        macd_histogram: macd.histogram[macd.histogram.length - 1],
        bb_upper: bb.upper[bb.upper.length - 1],
        bb_middle: bb.middle[bb.middle.length - 1],
        bb_lower: bb.lower[bb.lower.length - 1],
        atr: atr[atr.length - 1],
        volume_ratio: volumeRatio,
        momentum: momentum,
        volatility: volatility,
        support: supportResistance.support,
        resistance: supportResistance.resistance
      }
    }
    
    // ML辅助函数（简化实现）
    const calculateSMA = (data, period) => {
      const result = []
      for (let i = period - 1; i < data.length; i++) {
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += data[i - j]
        }
        result.push(sum / period)
      }
      return result
    }
    
    const calculateMACD = (prices) => {
      const ema12 = calculateEMA(prices, 12)
      const ema26 = calculateEMA(prices, 26)
      const macd = ema12.map((val, i) => val - ema26[i])
      const signal = calculateEMA(macd, 9)
      
      return {
        macd: macd,
        signal: signal,
        histogram: macd.map((val, i) => val - signal[i])
      }
    }
    
    const calculateEMA = (data, period) => {
      const result = []
      const multiplier = 2 / (period + 1)
      
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          result.push(data[i])
        } else {
          result.push((data[i] - result[i - 1]) * multiplier + result[i - 1])
        }
      }
      
      return result
    }
    
    const calculateBB = (prices, period, stdDevMultiplier) => {
      const result = []
      
      for (let i = period - 1; i < prices.length; i++) {
        // 计算中轨（移动平均线）
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += prices[i - j]
        }
        const middle = sum / period
        
        // 计算标准差
        let variance = 0
        for (let j = 0; j < period; j++) {
          const diff = prices[i - j] - middle
          variance += diff * diff
        }
        const stdDev = Math.sqrt(variance / period)
        
        // 计算上下轨
        const upper = middle + (stdDev * stdDevMultiplier)
        const lower = middle - (stdDev * stdDevMultiplier)
        
        result.push({ upper, middle, lower })
      }
      
      return result
    }
    
    const calculateATR = (data, period) => {
      const tr = []
      
      for (let i = 1; i < data.length; i++) {
        const high = data[i].high
        const low = data[i].low
        const close = data[i].close
        const prevClose = data[i - 1].close
        
        const tr1 = high - low
        const tr2 = Math.abs(high - prevClose)
        const tr3 = Math.abs(low - prevClose)
        
        tr.push(Math.max(tr1, tr2, tr3))
      }
      
      return calculateSMA(tr, period)
    }
    
    const calculateVolatility = (prices, period) => {
      const logReturns = []
      
      for (let i = 1; i < prices.length; i++) {
        const logReturn = Math.log(prices[i] / prices[i - 1])
        logReturns.push(logReturn)
      }
      
      const variance = logReturns.reduce((sum, val) => sum + val * val, 0) / logReturns.length
      return Math.sqrt(variance) * Math.sqrt(period)
    }
    
    const calculateSupportResistance = (data) => {
      const prices = data.map(d => d.close)
      const highs = data.map(d => d.high)
      const lows = data.map(d => d.low)
      
      const support = Math.min(...lows)
      const resistance = Math.max(...highs)
      
      return { support, resistance }
    }
    

    
    const calculateTrendSlope = (prices) => {
      if (prices.length < 2) return 0
      
      let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0
      const n = prices.length
      
      for (let i = 0; i < n; i++) {
        sumX += i
        sumY += prices[i]
        sumXY += i * prices[i]
        sumXX += i * i
      }
      
      const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
      return slope / (sumY / n) // 标准化斜率
    }

    const identifyMarketState = (data, index) => {
      const lookback = Math.min(50, index)
      const recentData = data.slice(index - lookback + 1, index + 1)
      const prices = recentData.map(d => d.close)
      
      const trendSlope = calculateTrendSlope(prices)
      const volatility = calculateVolatility(prices, Math.min(20, prices.length))
      
      if (Math.abs(trendSlope) < 0.001 && volatility < 0.02) {
        return 'sideways'
      } else if (trendSlope > 0.002) {
        return 'bull'
      } else if (trendSlope < -0.002) {
        return 'bear'
      } else {
        return 'neutral'
      }
    }
    
    // 优化：ML预测算法（增强版）
    const performMLPrediction = (features, marketState) => {
      const weights = getFeatureWeights(backtestSettings.mlFeatureWeighting)
      
      let buyScore = 0
      let sellScore = 0
      
      // 1. 趋势因子（增强版）
      const trendScore = calculateTrendScore(features)
      buyScore += trendScore.bullish * weights.trend
      sellScore += trendScore.bearish * weights.trend
      
      // 2. 动量因子（多层次）
      const momentumScore = calculateMomentumScore(features)
      buyScore += momentumScore.bullish * weights.momentum
      sellScore += momentumScore.bearish * weights.momentum
      
      // 3. 反转因子（精细化）
      const reversalScore = calculateReversalScore(features)
      buyScore += reversalScore.bullish * weights.reversal
      sellScore += reversalScore.bearish * weights.reversal
      
      // 4. 成交量因子（新增）
      const volumeScore = calculateVolumeScore(features)
      buyScore += volumeScore.bullish * weights.volume
      sellScore += volumeScore.bearish * weights.volume
      
      // 5. 波动性因子（新增）
      const volatilityScore = calculateVolatilityScore(features)
      buyScore += volatilityScore.adjustment
      sellScore -= volatilityScore.adjustment
      
      // 6. 市场状态调整（优化）
      const stateMultiplier = getMarketStateMultiplier(marketState, features)
      buyScore *= stateMultiplier.buy
      sellScore *= stateMultiplier.sell
      
      // 7. 情绪指标调整（增强）
      const sentimentFactor = calculateAdvancedSentimentIndicator(features, marketState)
      buyScore += sentimentFactor * backtestSettings.mlSentimentWeight
      sellScore -= sentimentFactor * backtestSettings.mlSentimentWeight
      
      // 8. 正则化评分（改进）
      const totalScore = Math.abs(buyScore) + Math.abs(sellScore)
      let normalizedBuyScore = totalScore > 0 ? Math.abs(buyScore) / totalScore : 0.5
      let normalizedSellScore = totalScore > 0 ? Math.abs(sellScore) / totalScore : 0.5
      
      // 9. 信号筛选和置信度计算
      let signal = 'hold'
      let confidence = 0
      
      const signalThreshold = 0.55 // 降低阈值提高灵敏度
      const strongSignalThreshold = 0.7 // 强信号阈值
      
      if (normalizedBuyScore > signalThreshold && normalizedBuyScore > normalizedSellScore) {
        signal = 'buy'
        confidence = normalizedBuyScore
        // 强信号额外加分
        if (normalizedBuyScore > strongSignalThreshold) {
          confidence = Math.min(0.95, confidence * 1.1)
        }
      } else if (normalizedSellScore > signalThreshold && normalizedSellScore > normalizedBuyScore) {
        signal = 'sell'
        confidence = normalizedSellScore
        // 强信号额外加分
        if (normalizedSellScore > strongSignalThreshold) {
          confidence = Math.min(0.95, confidence * 1.1)
        }
      }
      
      return {
        signal,
        confidence,
        buyScore: normalizedBuyScore,
        sellScore: normalizedSellScore,
        marketState,
        details: { // 新增：详细信息
          trendScore,
          momentumScore,
          reversalScore,
          volumeScore,
          volatilityScore,
          sentimentFactor
        }
      }
    }
    
    // 新增：趋势评分算法
    const calculateTrendScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 多层MA分析
      const maAlignment = {
        short: features.price > features.ma5 ? 1 : -1,
        medium: features.ma5 > features.ma20 ? 1 : -1,
        long: features.ma20 > features.ma50 ? 1 : -1
      }
      
      // MA排列评分
      const alignmentScore = (maAlignment.short + maAlignment.medium + maAlignment.long) / 3
      if (alignmentScore > 0.33) bullish += 0.4
      if (alignmentScore < -0.33) bearish += 0.4
      
      // 价格位置分析
      const pricePosition = {
        aboveMA5: (features.price - features.ma5) / features.ma5,
        aboveMA20: (features.price - features.ma20) / features.ma20
      }
      
      if (pricePosition.aboveMA5 > 0.02) bullish += 0.3
      if (pricePosition.aboveMA5 < -0.02) bearish += 0.3
      if (pricePosition.aboveMA20 > 0.05) bullish += 0.3
      if (pricePosition.aboveMA20 < -0.05) bearish += 0.3
      
      return { bullish, bearish }
    }
    
    // 新增：动量评分算法
    const calculateMomentumScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 价格动量
      if (features.momentum > 0.03) bullish += 0.5
      else if (features.momentum > 0.01) bullish += 0.3
      if (features.momentum < -0.03) bearish += 0.5
      else if (features.momentum < -0.01) bearish += 0.3
      
      // RSI动量
      if (features.rsi < 25) bullish += 0.4
      else if (features.rsi < 35) bullish += 0.2
      if (features.rsi > 75) bearish += 0.4
      else if (features.rsi > 65) bearish += 0.2
      
      // MACD动量
      if (features.macd_line > features.macd_signal && features.macd_histogram > 0) bullish += 0.3
      if (features.macd_line < features.macd_signal && features.macd_histogram < 0) bearish += 0.3
      
      // MACD金叉死叉加分
      const macdCrossover = features.macd_histogram > 0 && Math.abs(features.macd_histogram) > Math.abs(features.macd_line) * 0.1
      if (macdCrossover && features.macd_line > 0) bullish += 0.2
      if (!macdCrossover && features.macd_line < 0) bearish += 0.2
      
      return { bullish, bearish }
    }
    
    // 新增：反转评分算法
    const calculateReversalScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 布林带位置
      const bbPosition = (features.price - features.bb_lower) / (features.bb_upper - features.bb_lower)
      if (bbPosition < 0.15) bullish += 0.6 // 接近下轨
      else if (bbPosition < 0.25) bullish += 0.3
      if (bbPosition > 0.85) bearish += 0.6 // 接近上轨
      else if (bbPosition > 0.75) bearish += 0.3
      
      // 支撑阻力分析
      const supportDistance = (features.price - features.support) / features.support
      const resistanceDistance = (features.resistance - features.price) / features.price
      
      if (supportDistance < 0.015) bullish += 0.4 // 靠近支撑
      if (resistanceDistance < 0.015) bearish += 0.4 // 靠近阻力
      
      // 极端指标值
      if (features.rsi < 15) bullish += 0.5 // 极度超卖
      if (features.rsi > 85) bearish += 0.5 // 极度超买
      
      return { bullish, bearish }
    }
    
    // 新增：成交量评分算法
    const calculateVolumeScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 成交量放大程度
      if (features.volume_ratio > 2.5) {
        bullish += 0.4 // 大量放大通常是看涨信号
      } else if (features.volume_ratio > 1.8) {
        bullish += 0.2
      } else if (features.volume_ratio < 0.5) {
        bearish += 0.2 // 成交量萝缩可能是下跌信号
      }
      
      // 成交量与价格变化的关系
      if (features.volume_ratio > 1.5 && features.momentum > 0) {
        bullish += 0.3 // 量价齐升
      }
      
      if (features.volume_ratio > 1.5 && features.momentum < 0) {
        bearish += 0.3 // 量增价跌
      }
      
      return { bullish, bearish }
    }
    
    // 新增：波动性评分算法
    const calculateVolatilityScore = (features) => {
      let adjustment = 0
      
      // 波动性调整（低波动性适合交易，高波动性需谨慎）
      if (features.volatility < 0.015) {
        adjustment = 0.1 // 低波动性增加信心
      } else if (features.volatility > 0.08) {
        adjustment = -0.2 // 高波动性减少信心
      } else if (features.volatility > 0.05) {
        adjustment = -0.1
      }
      
      return { adjustment }
    }
    
    // 新增：市场状态乘数
    const getMarketStateMultiplier = (marketState, features) => {
      switch (marketState) {
        case 'bull':
          return { buy: 1.3, sell: 0.7 }
        case 'bear':
          return { buy: 0.6, sell: 1.4 }
        case 'sideways':
          // 震荡市适合反转交易
          return features.rsi < 30 || features.rsi > 70 ? 
            { buy: 1.1, sell: 1.1 } : { buy: 0.9, sell: 0.9 }
        default:
          return { buy: 1.0, sell: 1.0 }
      }
    }
    
    // 优化：高级情绪指标
    const calculateAdvancedSentimentIndicator = (features, marketState) => {
      let sentiment = 0
      
      // 1. 恐慌指数（VIX类似）
      const fearIndex = calculateFearIndex(features)
      if (fearIndex > 0.8) sentiment += 0.6 // 极度恐慌时反向买入
      else if (fearIndex > 0.6) sentiment += 0.3
      
      // 2. 贪婪指数
      const greedIndex = calculateGreedIndex(features)
      if (greedIndex > 0.8) sentiment -= 0.6 // 极度贪婪时谨慎
      else if (greedIndex > 0.6) sentiment -= 0.3
      
      // 3. 技术指标远离平衡
      const technicalExtreme = calculateTechnicalExtreme(features)
      sentiment += technicalExtreme * 0.4
      
      // 4. 市场状态调整
      if (marketState === 'bear' && sentiment > 0) {
        sentiment *= 1.2 // 熊市中的反转信号更强
      } else if (marketState === 'bull' && sentiment < 0) {
        sentiment *= 1.2 // 牛市中的顶部信号更强
      }
      
      return Math.max(-1, Math.min(1, sentiment))
    }
    
    // 恐慌指数计算
    const calculateFearIndex = (features) => {
      let fearScore = 0
      
      // RSI极低值
      if (features.rsi < 20) fearScore += 0.4
      else if (features.rsi < 30) fearScore += 0.2
      
      // 价格远低于布林带下轨
      if (features.price < features.bb_lower * 0.98) fearScore += 0.3
      
      // 高波动性环境
      if (features.volatility > 0.06) fearScore += 0.3
      
      return Math.min(1, fearScore)
    }
    
    // 贪婪指数计算
    const calculateGreedIndex = (features) => {
      let greedScore = 0
      
      // RSI极高值
      if (features.rsi > 80) greedScore += 0.4
      else if (features.rsi > 70) greedScore += 0.2
      
      // 价格远高于布林带上轨
      if (features.price > features.bb_upper * 1.02) greedScore += 0.3
      
      // 成交量异常放大
      if (features.volume_ratio > 3) greedScore += 0.3
      
      return Math.min(1, greedScore)
    }
    
    // 技术指标远离平衡
    const calculateTechnicalExtreme = (features) => {
      let extremeScore = 0
      
      // 多个指标同时超买/超卖
      const oversoldCount = [
        features.rsi < 25,
        features.price < features.bb_lower,
        features.momentum < -0.05
      ].filter(Boolean).length
      
      const overboughtCount = [
        features.rsi > 75,
        features.price > features.bb_upper,
        features.momentum > 0.05
      ].filter(Boolean).length
      
      if (oversoldCount >= 2) extremeScore += 0.5
      if (overboughtCount >= 2) extremeScore -= 0.5
      
      return extremeScore
    }
    
    // 保留原有的getFeatureWeights函数（并优化）
    const getFeatureWeights = (mode) => {
      switch (mode) {
        case 'trend_focused':
          return { trend: 0.5, momentum: 0.2, reversal: 0.2, volume: 0.1 }
        case 'momentum_focused':
          return { trend: 0.2, momentum: 0.5, reversal: 0.2, volume: 0.1 }
        case 'reversal_focused':
          return { trend: 0.2, momentum: 0.2, reversal: 0.5, volume: 0.1 }
        case 'balanced':
        default:
          return { trend: 0.3, momentum: 0.3, reversal: 0.3, volume: 0.1 }
      }
    }
    
    // 新增：风险评估函数
    const evaluateRiskConditions = (features, marketState, consecutiveLosses, cash, initialCapital) => {
      let allowBuy = true
      let forceSell = false
      
      // 1. 连续亏损风险控制
      if (consecutiveLosses >= 3) {
        allowBuy = false // 连续3次亏损后暂停交易
      }
      
      // 2. 资金水位风险控制
      const remainingCapitalRatio = cash / initialCapital
      if (remainingCapitalRatio < 0.3) {
        allowBuy = false // 资金低于30%暂停交易
      }
      
      // 3. 极端市场环境风险控制
      if (features.volatility > 0.1 && marketState === 'bear') {
        allowBuy = false // 高波动性熊市环境下不交易
        forceSell = true // 强制清仓
      }
      
      // 4. 技术指标极端值风险控制
      if (features.rsi > 90 || features.rsi < 10) {
        if (features.rsi > 90) forceSell = true
        if (features.rsi < 10) allowBuy = false // 极度超卖时谨慎交易
      }
      
      return { allowBuy, forceSell }
    }
    
    // 优化：动态仓位管理函数（考虑连续亏损）
    const calculateDynamicPosition = (features, prediction, basePercent, consecutiveLosses = 0) => {
      let positionMultiplier = 1
      
      // 基于置信度调整
      positionMultiplier *= prediction.confidence
      
      // 基于波动性调整
      if (features.volatility > 0.05) {
        positionMultiplier *= 0.6 // 更保守
      } else if (features.volatility < 0.02) {
        positionMultiplier *= 1.4 // 更激进
      }
      
      // 基于连续亏损调整
      if (consecutiveLosses > 0) {
        positionMultiplier *= Math.pow(0.8, consecutiveLosses) // 逐次减少仓位
      }
      
      // 基于市场状态调整
      if (features.volume_ratio > 2.0) {
        positionMultiplier *= 1.2 // 成交量放大时适度增加
      }
      
      return Math.max(3, Math.min(40, basePercent * positionMultiplier)) // 调整范围
    }
    
    const calculateAdaptiveStopLoss = (atr, multiplier) => {
      return atr * multiplier / 100
    }
    
    const calculateAdaptiveTakeProfit = (atr, confidence) => {
      const baseMultiplier = 2
      const confidenceMultiplier = confidence * 2
      return atr * (baseMultiplier + confidenceMultiplier) / 100
    }
    
    const checkMLStopConditions = (currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) => {
      if (!lastBuyPrice) return false
      
      const stopLossPrice = lastBuyPrice * (1 - adaptiveStopLoss)
      const takeProfitPrice = lastBuyPrice * (1 + adaptiveTakeProfit)
      
      return currentPrice <= stopLossPrice || currentPrice >= takeProfitPrice
    }
    
    // 实时ML策略信号生成
    const generateRealTimeMLStrategy1Signal = (priceHistory) => {
      if (priceHistory.length < 50) return null
      
      // 将价格历史转换为数据格式
      const data = priceHistory.map(p => ({
        date: p.date,
        close: p.close,
        high: p.close * 1.01, // 模拟高价
        low: p.close * 0.99,  // 模拟低价
        volume: 1000 + Math.random() * 1000 // 模拟成交量
      }))
      
      const index = data.length - 1
      const features = calculateMLFeatures(data, index)
      
      if (!features) return null
      
      let marketState = 'neutral'
      if (backtestSettings.mlMarketStateAware) {
        marketState = identifyMarketState(data, index)
      }
      
      const mlPrediction = performMLPrediction(features, marketState)
      
      if (mlPrediction.signal === 'buy' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position === 0) {
        return { 
          type: 'buy', 
          reason: `ML买入信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      if (mlPrediction.signal === 'sell' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position > 0) {
        return { 
          type: 'sell', 
          reason: `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      // 检查智能止损止盈
      if (virtualTradingResults.position > 0) {
        const lastBuyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        if (lastBuyTrade) {
          const adaptiveStopLoss = calculateAdaptiveStopLoss(features.atr, backtestSettings.mlAdaptiveStopLoss)
          const adaptiveTakeProfit = calculateAdaptiveTakeProfit(features.atr, mlPrediction.confidence)
          
          if (checkMLStopConditions(features.price, lastBuyTrade.price, adaptiveStopLoss, adaptiveTakeProfit)) {
            return { 
              type: 'sell', 
              reason: `智能止损止盈(ATR:${features.atr.toFixed(2)})` 
            }
          }
        }
      }
      
      return null
    }
    
    // 历史数据ML策略信号生成
    const generateMLStrategy1Signal = (data, currentIndex) => {
      const features = calculateMLFeatures(data, currentIndex)
      if (!features) return null
      
      let marketState = 'neutral'
      if (backtestSettings.mlMarketStateAware) {
        marketState = identifyMarketState(data, currentIndex)
      }
      
      const mlPrediction = performMLPrediction(features, marketState)
      
      if (mlPrediction.signal === 'buy' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position === 0) {
        return { 
          type: 'buy', 
          reason: `ML买入信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      if (mlPrediction.signal === 'sell' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position > 0) {
        return { 
          type: 'sell', 
          reason: `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      return null
    }
    
    // 计算回测结果
    const calculateBacktestResults = () => {
      if (!backtestResults.value || !backtestResults.value.equityCurve || !backtestResults.value.equityCurve.length) return
      
      const equityCurve = backtestResults.value.equityCurve
      const trades = backtestResults.value.trades
      
      // 计算总收益率
      const initialEquity = equityCurve[0].equity
      const finalEquity = equityCurve[equityCurve.length - 1].equity
      backtestSummary.totalReturn = ((finalEquity - initialEquity) / initialEquity) * 100
      
      // 计算年化收益率
      const days = equityCurve.length
      const years = days / 365
      backtestSummary.annualReturn = years > 0 ? (Math.pow(1 + backtestSummary.totalReturn / 100, 1 / years) - 1) * 100 : 0
      
      // 计算夏普比率
      const returns = []
      for (let i = 1; i < equityCurve.length; i++) {
        const ret = (equityCurve[i].equity - equityCurve[i - 1].equity) / equityCurve[i - 1].equity
        returns.push(ret)
      }
      
      const avgReturn = returns.length > 0 ? returns.reduce((a, b) => a + b, 0) / returns.length : 0
      const stdDev = returns.length > 1 ? Math.sqrt(returns.map(x => Math.pow(x - avgReturn, 2)).reduce((a, b) => a + b, 0) / returns.length) : 0
      backtestSummary.sharpeRatio = stdDev === 0 ? 0 : avgReturn / stdDev
      
      // 计算最大回撤
      let peak = initialEquity
      let maxDrawdown = 0
      
      for (const item of equityCurve) {
        if (item.equity > peak) peak = item.equity
        const drawdown = (peak - item.equity) / peak
        if (drawdown > maxDrawdown) maxDrawdown = drawdown
      }
      
      backtestSummary.maxDrawdown = maxDrawdown * 100
      
      // 计算胜率
      const profitableTrades = trades.filter(t => t.profit && t.profit > 0).length
      backtestSummary.totalTrades = trades.filter(t => t.profit !== undefined).length
      backtestSummary.winRate = backtestSummary.totalTrades > 0 ? (profitableTrades / backtestSummary.totalTrades) * 100 : 0
    }
    
    // 绘制回测结果图表
    const drawBacktestChart = (results) => {
      if (!backtestChart.value || !results || !results.equityCurve || !results.equityCurve.length) {
        console.warn('图表容器或数据不存在')
        return
      }
      
      // 销毁旧图表实例
      if (backtestChartInstance.value) {
        backtestChartInstance.value.dispose()
        backtestChartInstance.value = null
      }
      
      // 初始化图表
      backtestChartInstance.value = echarts.init(backtestChart.value)
      
      // 准备图表数据
      const dates = results.equityCurve.map(item => item.date)
      const equityValues = results.equityCurve.map(item => item.equity)
      
      const option = {
        title: {
          text: '回测结果 - 权益曲线',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = params[0].axisValue
            const value = params[0].data.toFixed(2)
            return `${date}<br/>权益: $${value}`
          }
        },
        xAxis: {
          type: 'category',
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          axisLabel: {
            formatter: function(value) {
              return value.split(' ')[0] // 只显示日期部分
            }
          }
        },
        yAxis: {
          type: 'value',
          scale: true,
          splitLine: { show: true },
          axisLabel: {
            formatter: '${value}'
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '权益',
            type: 'line',
            data: equityValues,
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 2,
              color: '#5470c6'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(84, 112, 198, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(84, 112, 198, 0.1)'
                }
              ])
            }
          }
        ]
      }
      
      backtestChartInstance.value.setOption(option)
      
      // 响应窗口大小变化
      const resizeHandler = () => {
        if (backtestChartInstance.value) {
          backtestChartInstance.value.resize()
        }
      }
      window.addEventListener('resize', resizeHandler)
    }
    
    // 保存策略
    const saveStrategy = () => {
      if (!backtestResults.value.equityCurve || !backtestResults.value.equityCurve.length) {
        ElMessage({
          message: '请先运行回测',
          type: 'warning'
        })
        return
      }
      
      ElMessageBox.prompt('请输入策略名称', '保存策略', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '策略名称不能为空'
      }).then(({ value }) => {
        // 保存策略到本地存储
        const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
        
        const strategyToSave = {
          id: Date.now(),
          name: value,
          settings: { ...backtestSettings },
          summary: { ...backtestSummary },
          savedAt: new Date().toLocaleString()
        }
        
        savedStrategies.push(strategyToSave)
        localStorage.setItem('backtestStrategies', JSON.stringify(savedStrategies))
        
        ElMessage({
          message: `策略 "${value}" 已保存`,
          type: 'success'
        })
      }).catch(() => {
        // 取消保存
      })
    }
    
    // 加载策略
    const loadStrategy = () => {
      // 从本地存储获取已保存的策略
      const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
      
      if (savedStrategies.length === 0) {
        ElMessage({
          message: '没有找到已保存的策略',
          type: 'info'
        })
        return
      }
      
      // 准备策略列表
      const options = savedStrategies.map(strategy => ({
        label: `${strategy.name} (${strategy.savedAt}) - 收益率: ${strategy.summary.totalReturn.toFixed(2)}%`,
        value: strategy.id
      }))
      
      // 显示策略选择对话框
      ElMessageBox.select('选择要加载的策略', '加载策略', options, {
        confirmButtonText: '加载',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        // 查找选中的策略
        const selectedStrategy = savedStrategies.find(s => s.id === value)
        
        if (selectedStrategy) {
          // 加载策略设置
          Object.assign(backtestSettings, selectedStrategy.settings)
          
          ElMessage({
            message: `策略 "${selectedStrategy.name}" 已加载`,
            type: 'success'
          })
          
          // 清空当前回测结果
          backtestResults.value = { equityCurve: [], trades: [] }
          backtestTrades.value = []
          
          // 如果有图表实例，清除图表
          if (backtestChartInstance.value) {
            backtestChartInstance.value.clear()
          }
        }
      }).catch(() => {
        // 取消加载
      })
    }
    
    // 新增：策略性能分析函数
    const calculateStrategyPerformance = (results) => {
      const trades = results.trades || []
      const signals = results.signals || []
      const equityCurve = results.equityCurve || []
      
      if (trades.length === 0) return {}
      
      // 信号质量分析
      const signalQuality = {
        totalSignals: signals.length,
        avgConfidence: signals.length > 0 ? signals.reduce((sum, s) => sum + (s.confidence || 0), 0) / signals.length : 0,
        strongSignals: signals.filter(s => s.confidence > 0.8).length,
        weakSignals: signals.filter(s => s.confidence < 0.6).length
      }
      
      // 交易效率分析
      const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
      const profitableTrades = sellTrades.filter(t => t.profit > 0)
      
      const efficiency = {
        signalToTradeRatio: trades.length / Math.max(signals.length, 1),
        profitableTradeRatio: profitableTrades.length / Math.max(sellTrades.length, 1),
        avgHoldingPeriod: calculateAvgHoldingPeriod(trades),
        maxConsecutiveWins: calculateMaxConsecutive(sellTrades, true),
        maxConsecutiveLosses: calculateMaxConsecutive(sellTrades, false)
      }
      
      // 风险指标
      const riskMetrics = {
        maxDrawdown: calculateMaxDrawdownFromCurve(equityCurve),
        volatility: calculateEquityVolatility(equityCurve),
        riskAdjustedReturn: calculateRiskAdjustedReturn(equityCurve)
      }
      
      return {
        signalQuality,
        efficiency,
        riskMetrics,
        recommendation: generateStrategyRecommendation(signalQuality, efficiency, riskMetrics)
      }
    }
    
    // 辅助函数
    const calculateAvgHoldingPeriod = (trades) => {
      const pairs = []
      let buyTrade = null
      
      for (const trade of trades) {
        if (trade.type === 'buy') {
          buyTrade = trade
        } else if (trade.type === 'sell' && buyTrade) {
          const buyDate = new Date(buyTrade.date)
          const sellDate = new Date(trade.date)
          pairs.push((sellDate - buyDate) / (1000 * 60 * 60 * 24)) // 天数
          buyTrade = null
        }
      }
      
      return pairs.length > 0 ? pairs.reduce((a, b) => a + b, 0) / pairs.length : 0
    }
    
    const calculateMaxConsecutive = (trades, isWin) => {
      let maxCount = 0
      let currentCount = 0
      
      for (const trade of trades) {
        const condition = isWin ? trade.profit > 0 : trade.profit <= 0
        if (condition) {
          currentCount++
          maxCount = Math.max(maxCount, currentCount)
        } else {
          currentCount = 0
        }
      }
      
      return maxCount
    }
    
    const calculateMaxDrawdownFromCurve = (equityCurve) => {
      if (equityCurve.length === 0) return 0
      
      let maxEquity = equityCurve[0].equity
      let maxDrawdown = 0
      
      for (const point of equityCurve) {
        maxEquity = Math.max(maxEquity, point.equity)
        const drawdown = (maxEquity - point.equity) / maxEquity
        maxDrawdown = Math.max(maxDrawdown, drawdown)
      }
      
      return maxDrawdown * 100
    }
    
    const calculateEquityVolatility = (equityCurve) => {
      if (equityCurve.length < 2) return 0
      
      const returns = []
      for (let i = 1; i < equityCurve.length; i++) {
        const ret = (equityCurve[i].equity - equityCurve[i-1].equity) / equityCurve[i-1].equity
        returns.push(ret)
      }
      
      const mean = returns.reduce((a, b) => a + b, 0) / returns.length
      const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length
      
      return Math.sqrt(variance) * 100
    }
    
    const calculateRiskAdjustedReturn = (equityCurve) => {
      if (equityCurve.length === 0) return 0
      
      const totalReturn = (equityCurve[equityCurve.length - 1].equity - equityCurve[0].equity) / equityCurve[0].equity
      const volatility = calculateEquityVolatility(equityCurve) / 100
      
      return volatility > 0 ? totalReturn / volatility : 0
    }
    
    const generateStrategyRecommendation = (signalQuality, efficiency, riskMetrics) => {
      const recommendations = []
      
      // 信号质量建议
      if (signalQuality.avgConfidence < 0.7) {
        recommendations.push('建议提高置信度阈值或调整特征权重')
      }
      
      if (signalQuality.totalSignals > 0 && signalQuality.weakSignals / signalQuality.totalSignals > 0.4) {
        recommendations.push('弱信号过多，考虑开启风险过滤器')
      }
      
      // 交易效率建议
      if (efficiency.profitableTradeRatio < 0.5) {
        recommendations.push('胜率较低，建议优化止损止盈参数')
      }
      
      if (efficiency.maxConsecutiveLosses > 5) {
        recommendations.push('连续亏损过多，建议开启动态仓位管理')
      }
      
      // 风险控制建议
      if (riskMetrics.maxDrawdown > 20) {
        recommendations.push('最大回撤过大，建议降低仓位或加强风险控制')
      }
      
      if (riskMetrics.volatility > 15) {
        recommendations.push('策略波动性较大，建议调整情绪指标权重')
      }
      
      return recommendations.length > 0 ? recommendations : ['策略表现良好，可继续使用']
    }


    
    return {
      // 数据源相关
      dataSources,
      selectedDataSource,
      isLoading,
      lastUpdated,
      fetchDataBySource,
      fetchAllDataSources,
      autoRefresh,
      toggleAutoRefresh,
      
      // 市场数据
      marketOverview,
      symbols,
      selectedSymbol,
      binanceSymbol,
      binanceWebview,
      binanceCurrentPrice,
      updateBinanceChart,
      startBinancePriceMonitoring,
      stopBinancePriceMonitoring,
      
      // 比较数据
      comparisonData,
      
      // 回测相关
      backtestSettings,
      isBacktesting,
      backtestResults,
      backtestTrades,
      backtestSummary,
      backtestChart,
      runBacktest,
      saveStrategy,
      loadStrategy,
      
      // 虚拟交易相关
      isVirtualTrading,
      virtualTradingResults,
      virtualTradingStatistics,
      startVirtualTrading,
      stopVirtualTrading,
      saveVirtualTradingState,
      loadVirtualTradingState,
      restoreVirtualTradingState,
      clearVirtualTradingState,
      exportVirtualTradingData,
      calculateVirtualTradingStatistics,
      manualSaveState
    }
  }
}
</script>

<style scoped>
.trading-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.market-item {
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
  text-align: center;
  margin-bottom: 10px;
}

.market-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-price {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-change {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.trading-chart {
  width: 100%;
  height: 100%;
}

.binance-webview {
  width: 100%;
  height: 700px;
  border: none;
  display: inline-flex;
}

.buy-btn {
  background-color: #14b143;
  border-color: #14b143;
}

.sell-btn {
  background-color: #ef232a;
  border-color: #ef232a;
}

.asset-overview {
  padding: 10px 0;
}

.asset-item {
  text-align: center;
  margin-bottom: 10px;
}

.asset-label {
  font-size: 14px;
  color: #909399;
}

.asset-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.asset-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
}

.asset-name {
  font-weight: bold;
}

.asset-balance {
  color: #606266;
}

.data-source-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.last-updated {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
}

.price-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.price-cell div:first-child {
  font-weight: bold;
  margin-bottom: 4px;
}

.price-diff .warning {
  color: #e6a23c;
  font-weight: bold;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}

/* 虚拟交易相关样式 */
.virtual-stat-item {
  text-align: center;
  padding: 10px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #fde68a;
}

.virtual-stat-item .stat-label {
  font-size: 12px;
  color: #92400e;
  margin-bottom: 5px;
}

.virtual-stat-item .stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #451a03;
}

.virtual-stat-item .stat-value.profit {
  color: #14b143;
}

.virtual-stat-item .stat-value.loss {
  color: #ef232a;
}

.trade-record {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 5px;
  border-radius: 4px;
  font-size: 12px;
  background: #fff;
  border-left: 3px solid #ddd;
}

.trade-record.buy {
  border-left-color: #14b143;
  background: #f0f9f4;
}

.trade-record.sell {
  border-left-color: #ef232a;
  background: #fef2f2;
}

.trade-type {
  font-weight: bold;
  min-width: 40px;
}

.trade-price {
  min-width: 60px;
  color: #1f2937;
}

.trade-amount {
  min-width: 60px;
  color: #6b7280;
}

.trade-reason {
  flex: 1;
  text-align: center;
  color: #374151;
}

.trade-time {
  min-width: 60px;
  color: #9ca3af;
  font-size: 11px;
}

.trade-profit {
  min-width: 60px;
  font-weight: bold;
  text-align: right;
}

.trade-profit.profit {
  color: #14b143;
}

.trade-profit.loss {
  color: #ef232a;
}

/* 统计卡片样式 */
.stat-card {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #1e293b;
  margin-bottom: 4px;
  line-height: 1.2;
}

.stat-detail {
  font-size: 11px;
  color: #94a3b8;
  line-height: 1.3;
}

.stat-number.neutral {
  color: #f59e0b;
}
</style>